Python Course
File handling is essential in any application that involves reading or writing data persistently. Python provides built-in functions and syntax to handle files—both text and binary—with ease.
File handling refers to the ability of a program to:
- Create files
- Read from files
- Write to files
- Delete or move files
This is crucial when:
- We want to store data beyond the program’s runtime (e.g., saving a game, chat logs).
- We want to read from configuration files.
- We want to process user data from documents, CSVs, logs, etc.
Types of Files
Type Examples Use Case Example ------ ----------------------- ---------------------------------- Text .txt, .csv, .json Store logs, notes, structured data Binary .jpg, .exe, .pdf Images, compiled code, backups
How Python Handles Files?
Python provides the built-in open() function to access files. It returns a file object, which gives you access to methods for reading or writing.
file_object = open("filename.txt", "mode") # work with the file file_object.close()
Common File Modes
Mode Description ----- ---------------------------------- r Read (default mode) w Write (creates/truncates file) a Append (writes at the end) x Create (fails if file exists) b Binary mode (e.g., rb, wb) t Text mode (default)
Reading a File
There are three main methods to read from a text file:
read()– reads the entire file content
with open("welcome.txt", "r") as file: content = file.read() print(content)
readline()– reads a single line
with open("welcome.txt", "r") as file: line1 = file.readline() print("First line:", line1)
readlines()– returns all lines as a list
with open("welcome.txt", "r") as file: lines = file.readlines() for line in lines: print(line.strip()) # strip() removes newline character
Let's see an example, we are building a support tool that reads only ERROR logs from a file.
# Read only error lines from a log file with open("system.log", "r") as log_file: for line in log_file: if "ERROR" in line: print("[!] Error Found:", line.strip())
If you see here,
- File is opened in read mode (
r). - Each line is checked for the word
ERROR. - Matching lines are printed.
Closing Files
If you open a file using open() (without with), you should always close it:
file = open("sample.txt", "r") # ... work with file ... file.close()
Why closing is important:
- Prevents memory leaks
- Ensures changes are saved
- Releases system resources
Preferred method:
Use with open(...)
- Automatically closes the file after the block ends
- Cleaner and safer
Examples for Reading a File
Print File with Line Numbers
with open("notes.txt", "r") as f: for idx, line in enumerate(f, start=1): print(f"Line {idx}: {line.strip()}")
Read Last N Lines (like tail)
Let's read the last 3 lines of a file.
def tail(filename, n=3): with open(filename, "r") as f: lines = f.readlines() for line in lines[-n:]: print(line.strip()) tail("notes.txt", 3)
Here with the pointers which i want to highlight especially while reading files.
- Use
open()to work with files. - Always close files — use
withto manage this automatically. - Choose the right method:
read(),readline(), orreadlines()based on your needs. - Reading files is a critical task in logs, configs, user data, and more.
Read a Json File
data.json
[ { "id": "1", "name": "Praveen", "age": 39, "salary": "50 LPA", "location": "Hyderabad" }, { "id": "2", "name": "Ravi", "age": 42, "salary": "40 LPA", "location": "Chennai" } ]
parse_json.py
import json # Open and load the JSON file with open('data.json', 'r') as file: info = json.load(file) # Print the data print('Employee count:', len(info)) for item in info: print('Id', item['id']) print('Name', item['name']) print('Age', item['age']) print('Salary', item['salary']) print('Location', item['location'])
Writing Files
- Writing to Files Using .write()
The .write() method lets you write a string to a file. If the file doesn’t exist, it will be created. If it does exist, it will be overwritten (truncated to zero length).
name = input("Enter your name: ") with open("profile.txt", "w") as f: f.write(f"Name: {name}")
Please note using "w" will delete existing content if any in the file.
- Writing Multiple Lines Using .writelines()
The .writelines() method writes a list of strings to the file. We are responsible for adding \n line breaks.
lines = ["Line 1\n", "Line 2\n", "Line 3\n"] with open("multi_lines.txt", "w") as f: f.writelines(lines)
- Appending to Files Using "a" Mode
Use the a mode to append content at the end of a file without deleting existing data.
note = input("Write your note: ") with open("notes.txt", "a") as f: f.write(note + "\n")
This is useful for:
- Logging events
- Saving form submissions
- Building cumulative data
Let's see an example, In a point-of-sale system, we want to save each transaction into a log file.
import datetime def log_transaction(item, price): with open("sales.txt", "a") as f: timestamp = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") f.write(f"{timestamp} | Item: {item} | Price: ${price}\n") log_transaction("Coffee", 2.99) log_transaction("Sandwich", 4.50)
If you see here,
- we are using
ato keep previous transactions - we are logging the time of each sale
Working with Binary Files
Unlike text files that store readable characters, binary files store raw bytes of data. These include:
- Images (
.jpg,.png) - Videos (
.mp4) - Audio files (
.mp3,.wav) - Executables (
.exe) - PDFs and office documents
We can’'t open and read them with a text editor properly—they require binary-aware tools.
Opening Binary Files
To work with binary files, use file modes that include b:
rb– read binarywb– write binaryab– append binary
Reading a Binary File
Lets read an Image File
with open("image.jpg", "rb") as img: binary_data = img.read() print(f"Read {len(binary_data)} bytes.")
Here if you see,
rbmeans read in binary mode.binary_datais a bytes object.- We can store or process it, or send it over a network.
Writing a Binary File
Lets copy a Binary File
with open("image.jpg", "rb") as original, open("copy.jpg", "wb") as duplicate: duplicate.write(original.read())
If you see here,
- Opens the source file in
rbmode. - Reads the raw bytes.
- Writes them to a new file in
wbmode.
Let's see an example where we need to backup pdf document.
def backup_file(source, destination): with open(source, "rb") as src_file: with open(destination, "wb") as dst_file: dst_file.write(src_file.read()) print(f"Backup completed: {destination}") backup_file("invoice.pdf", "invoice_backup.pdf")
Combining Text and Binary Handling
Sometimes we want to read metadata (e.g., filenames) from a text file and then handle corresponding binary files.
# file_list.txt contains: # image1.jpg # image2.jpg with open("file_list.txt", "r") as list_file: for filename in list_file: filename = filename.strip() with open(filename, "rb") as f: print(f"{filename} has {len(f.read())} bytes")