File handling is a core part of many real-world applications—whether you're storing data, reading configuration files, or writing logs. Python makes file operations straightforward with its built-in functions for reading, writing, and appending files using the open()
function.
In this tutorial, you'll learn how to handle files in Python with practical examples using modes like 'r'
, 'w'
, 'a'
, and 'x'
.
1. Opening a File in Python
You open a file using the open()
function. Its syntax is:
file = open("filename.txt", "mode")
Common file modes:
'r'
– Read (default)'w'
– Write (creates new file or truncates existing one)'a'
– Append (creates file if it doesn’t exist)'x'
– Create (fails if file exists)'b'
– Binary mode't'
– Text mode (default)
2. Reading from a File
# Example 1: Reading entire content
file = open("example.txt", "r")
content = file.read()
print(content)
file.close()
# Example 2: Reading line by line
file = open("example.txt", "r")
for line in file:
print(line.strip())
file.close()
3. Writing to a File
Using 'w'
mode will overwrite the file if it exists.
# Example 3: Writing to a file
file = open("data.txt", "w")
file.write("Python is powerful.\n")
file.write("File handling is easy.")
file.close()
4. Appending to a File
'a'
mode adds content to the end of the file without erasing the existing data.
# Example 4: Appending to a file
file = open("data.txt", "a")
file.write("\nThis line is appended.")
file.close()
5. Using with
Statement (Best Practice)
The with
statement automatically closes the file, even if an error occurs.
# Example 5: Using 'with' to read
with open("data.txt", "r") as file:
print(file.read())
# Example 6: Using 'with' to write
with open("newfile.txt", "w") as file:
file.write("This file was created using 'with'.")
6. Reading Files into a List
# Example 7: Reading all lines into a list
with open("data.txt", "r") as file:
lines = file.readlines()
print(lines)
7. Check if File Exists
import os
if os.path.exists("data.txt"):
print("File exists")
else:
print("File does not exist")
8. Deleting a File
import os
if os.path.exists("oldfile.txt"):
os.remove("oldfile.txt")
else:
print("The file does not exist")
9. Creating a New File (Safely)
# Example 8: Creating a new file safely
try:
file = open("newdoc.txt", "x")
file.write("Created a new document.")
file.close()
except FileExistsError:
print("File already exists.")
10. Summary Table
Mode | Description | Behavior |
---|---|---|
'r' |
Read | Opens file for reading (error if file doesn't exist) |
'w' |
Write | Creates file or overwrites existing one |
'a' |
Append | Adds to end of file (creates if missing) |
'x' |
Create | Fails if file already exists |
11. Final Thoughts
Python’s file handling is clean and beginner-friendly. By learning how to read, write, append, and delete files, you open up a whole new world of possibilities—from logging, report generation, and data storage to configuration management. Always remember to use the with
statement for safer file operations.