File handling is an essential part of programming, allowing you to store, retrieve, and manipulate data persistently. Python provides built-in functions for working with files, supporting operations like reading, writing, and appending in different modes (text, binary, etc.).
1. Opening a File in Python (open()
)
The open()
function is used to open a file in different modes:
Syntax:
file = open("filename.txt", "mode")
Mode | Meaning |
---|---|
"r" | Read mode (default) |
"w" | Write mode (overwrites file if it exists) |
"a" | Append mode (adds to existing file) |
"x" | Exclusive creation (fails if file exists) |
"b" | Binary mode (for non-text files) |
"t" | Text mode (default) |
2. Reading Files (r
mode)
The "r"
mode is used to read the contents of a file.
Example: Reading an Entire File
file = open("sample.txt", "r") # Open file in read mode
content = file.read() # Read entire file
print(content)
file.close() # Close the file
Important: Always close files after use to free system resources.
Reading Line by Line (readline()
)
file = open("sample.txt", "r")
line1 = file.readline() # Reads the first line
print(line1)
file.close()
Reading All Lines as a List (readlines()
)
file = open("sample.txt", "r")
lines = file.readlines() # Reads all lines into a list
print(lines)
file.close()
Tip: readlines()
is useful when you need to process each line separately.
3. Writing to Files (w
mode)
The "w"
mode is used to write data to a file. If the file exists, it is overwritten.
Example: Writing to a File
file = open("output.txt", "w")
file.write("Hello, World!\n")
file.write("This is a new file.\n")
file.close()
Warning: If output.txt
already exists, it will be erased before writing.
4. Appending to Files (a
mode)
The "a"
mode adds new content to an existing file without deleting previous data.
Example: Appending to a File
file = open("output.txt", "a")
file.write("Appending this line.\n")
file.close()
Use "a"
mode when you want to preserve existing data and add new content.
5. Using with
Statement (Best Practice)
The with
statement automatically closes the file after use.
Example: Reading a File with with
with open("sample.txt", "r") as file:
content = file.read()
print(content) # File is automatically closed after the block
Why use with
?
- No need to manually call
close()
. - Avoids errors if an exception occurs before closing.
6. Working with Binary Files (b
mode)
For non-text files (images, PDFs, etc.), use binary mode (b
).
Example: Reading a Binary File
with open("image.jpg", "rb") as file:
data = file.read()
print(data[:10]) # Print first 10 bytes
Example: Writing a Binary File
with open("copy.jpg", "wb") as file:
file.write(data) # Writes binary data
Binary mode is required for non-text files like images, videos, and executables.
7. Checking if a File Exists (Using os
and pathlib
)
Method 1: Using os
Module
import os
if os.path.exists("sample.txt"):
print("File exists")
else:
print("File does not exist")
Method 2: Using pathlib
(Recommended)
from pathlib import Path
file = Path("sample.txt")
if file.exists():
print("File exists")
pathlib
is preferred for modern Python versions (3.6+
).
8. File Handling Exceptions (try-except
)
Handling errors prevents crashes when a file is missing or unreadable.
Example: Handling File Errors
try:
with open("missing.txt", "r") as file:
content = file.read()
print(content)
except FileNotFoundError:
print("Error: File not found!")
except PermissionError:
print("Error: No permission to read file!")
Use try-except
to handle missing files gracefully.
9. Writing Lists to a File (writelines()
)
To write multiple lines, use writelines()
.
Example: Writing a List of Lines
lines = ["Line 1\n", "Line 2\n", "Line 3\n"]
with open("output.txt", "w") as file:
file.writelines(lines)
10. Reading Large Files Efficiently
For large files, read line by line using a loop instead of read()
.
Example: Efficient File Reading
with open("large_file.txt", "r") as file:
for line in file:
print(line.strip()) # Reads line-by-line (efficient)
Why?
- Avoids loading the entire file into memory.
- Useful for large log files, CSVs, and big datasets.
11. Renaming and Deleting Files (os
module)
Renaming a File
import os
os.rename("old_name.txt", "new_name.txt")
Deleting a File
os.remove("file_to_delete.txt")
Use with caution! Deleting a file cannot be undone.
12. File Handling Summary
Operation | Mode | Example |
---|---|---|
Read entire file | "r" | file.read() |
Read one line | "r" | file.readline() |
Read all lines | "r" | file.readlines() |
Write (overwrite) | "w" | file.write("text") |
Append to file | "a" | file.write("text") |
Binary read | "rb" | file.read() |
Binary write | "wb" | file.write(data) |
Safe file handling | with open() | Avoids close() |