File Handling in Python – Read, Write, Append
What is File Handling in Python?
File handling in Python allows you to create, read, write, and append to files directly from your Python code. Python provides built-in functions to perform these operations using the open() function.
Python open() Function Syntax
open(file_name, mode)
File Modes
- 'r' - Read (default)
- 'w' - Write (overwrite)
- 'a' - Append
- 'x' - Create a new file
- 'b' - Binary mode
- 't' - Text mode (default)
- '+' - Read and write
Reading a File in Python
# file: sample.txt
# Content:
# Hello, Python World!
f = open('sample.txt', 'r')
content = f.read()
print(content)
f.close()
Output:
Hello, Python World!
Pro Tip:
You can also use:
with open('sample.txt', 'r') as f:
content = f.read()
This automatically closes the file after reading.
Writing to a File in Python
f = open('sample.txt', 'w')
f.write('This will overwrite the file.\n')
f.write('Line two.')
f.close()
Result in sample.txt:
This will overwrite the file. Line two.
Note: The 'w' mode clears existing content before writing.
Appending to a File in Python
f = open('sample.txt', 'a')
f.write('\nThis line is appended.')
f.close()
Result in sample.txt:
This will overwrite the file. Line two. This line is appended.
Reading Line by Line
with open('sample.txt', 'r') as f:
for line in f:
print(line.strip())
Output:
This will overwrite the file. Line two. This line is appended.
Deleting a File
import os
if os.path.exists("sample.txt"):
os.remove("sample.txt")
else:
print("File does not exist")
Best Practices for File Handling
- Always use with open() — it handles closing automatically.
- Use try-except to catch file errors.
- Prefer relative paths for portability.