Python File Handling
What is File Handling in Python?
File handling allows you to create, read, write, append, and delete files (text or binary) using Python’s built-in functions. It's essential for tasks like reading logs, saving data, or processing files.
1. Opening a File with open()
file = open("example.txt", "r") # "r" means read mode
print(file.read())
file.close()
Modes:
Mode | Description |
---|---|
'r' | Read (default) |
'w' | Write (overwrite) |
'a' | Append (add to file) |
'x' | Create (error if exists) |
'b' | Binary mode |
't' | Text mode (default) |
2. Reading a File
Read Entire File
with open("example.txt", "r") as f:
content = f.read()
print(content)
Read Line by Line
with open("example.txt", "r") as f:
for line in f:
print(line.strip())
Read First N Characters
with open("example.txt", "r") as f:
print(f.read(10)) # Read first 10 chars
3. Writing to a File (w
)
with open("output.txt", "w") as f:
f.write("Hello World\n")
f.write("Welcome to Python!")
Note: This will overwrite the file if it exists.
4. Appending to a File (a
)
with open("output.txt", "a") as f:
f.write("\nThis is an additional line.")
5. Writing a List to a File
lines = ["Line 1\n", "Line 2\n", "Line 3\n"]
with open("list.txt", "w") as f:
f.writelines(lines)
6. Reading as a List of Lines
with open("list.txt", "r") as f:
lines = f.readlines()
print(lines)
Output:
['Line 1\n', 'Line 2\n', 'Line 3\n']
7. Checking If File Exists
import os
if os.path.exists("list.txt"):
print("File found!")
else:
print("File not found.")
8. Deleting a File
import os
os.remove("list.txt")
Note: Always check existence before deleting!
9. Create a File If Not Exists (x
)
with open("newfile.txt", "x") as f:
f.write("New file created.")
10. File Modes Summary Table
Mode | Action | Creates File | Overwrites |
---|---|---|---|
r | Read | No | No |
w | Write | Yes | Yes |
a | Append | Yes | No |
x | Create (error if exists) | Yes | No |
r+ | Read + Write | No | No |
Example: Copy Content from One File to Another
with open("source.txt", "r") as src, open("dest.txt", "w") as dest:
for line in src:
dest.write(line)