File handling in Python allows you to read from and write to files on your computer. This is essential when you want to save data permanently, rather than losing it when your program closes.
Basic Steps
- Open the file.
- Read or Write data.
- Close the file (to save memory and prevent data corruption).
File Opening Modes
'r'(Read): Default mode. Opens a file for reading. (Throws an error if the file doesn't exist).'w'(Write): Opens for writing. Overwrites the file if it exists, or creates a new one.'a'(Append): Opens for writing. Adds new data to the end of the file, or creates a new one.'x'(Create): Creates a new file. (Throws an error if the file already exists).'b'(Binary): Used for binary files like images or PDFs (e.g.,'rb','wb').
1. Basic File Reading
Suppose we have a file named data.txt with the text "Hello World".
file = open("data.txt", "r")
content = file.read()
print(content)
file.close() # ALWAYS close the file!
Output:
Hello World
2. The with Statement (Best Practice)
Instead of manually using file.close(), always use the with statement. It automatically closes the file for you, even if an error occurs!
with open("data.txt", "r") as file:
content = file.read()
print(content)
# The file is automatically closed here.
3. Reading Line by Line (readline)
readline() reads exactly one line at a time.
# Assuming names.txt contains:
# Ram
# Sita
with open("names.txt", "r") as file:
line1 = file.readline()
line2 = file.readline()
print(line1.strip()) # .strip() removes the hidden newline character (\n)
print(line2.strip())
Ram
Sita
4. Reading All Lines into a List (readlines)
readlines() returns a Python list containing every line.
with open("names.txt", "r") as file:
lines = file.readlines()
print(lines)
Output:
['Ram\n', 'Sita\n']
5. Iterating Through a File Using a Loop
This is the most memory-efficient way to read a large file.
with open("names.txt", "r") as file:
for line in file:
print(line.strip())
Output:
Ram
Sita
6. Writing to a File (w mode)
Warning: 'w' mode will completely erase existing content in the file before writing!
with open("output.txt", "w") as file:
file.write("This is the first line.\n")
file.write("This is the second line.\n")
print("File written successfully!")
7. Appending to a File (a mode)
To add data without erasing the old data, use 'a'.
with open("output.txt", "a") as file:
file.write("This line is added at the end.\n")
8. Creating a New File (x mode)
Prevents accidentally overwriting an existing file.
try:
with open("new_file.txt", "x") as file:
file.write("Created a brand new file!")
except FileExistsError:
print("Error: That file already exists!")
9. Handling File Errors gracefully
Always combine file handling with exception handling (which you just learned!).
try:
with open("missing_file.txt", "r") as file:
print(file.read())
except FileNotFoundError:
print("Oops! The file does not exist.")
Output:
Oops! The file does not exist.
10. Checking if a File Exists (os.path.exists)
You can use the built-in os module to check for a file before opening it.
import os
if os.path.exists("data.txt"):
print("File found!")
else:
print("File not found.")
11. Deleting a File (os.remove)
You also use the os module to delete files.
import os
if os.path.exists("old_data.txt"):
os.remove("old_data.txt")
print("File deleted.")
else:
print("The file does not exist.")
12. Reading and Writing at the Same Time (r+)
'r+' allows you to read and write. It does not delete the file content, but it starts writing from the beginning (overwriting character by character).
with open("data.txt", "r+") as file:
content = file.read()
print("Old content:", content)
file.write("\nAdding new text!")
13. Writing Multiple Lines at Once (writelines)
You can write a list of strings directly to a file.
lines_to_add = ["First line\n", "Second line\n", "Third line\n"]
with open("multiple.txt", "w") as file:
file.writelines(lines_to_add)
Important Points to Remember
open("file.txt", "r")→ Read (default)open("file.txt", "w")→ Write (overwrites)open("file.txt", "a")→ Append (adds to end)- Always use
with open(...) as file:so you never forget to close the file. .read()reads the whole file as one big string..readlines()reads the file into a list of strings..strip()is your best friend when reading files to remove unwanted\n(newline) characters.