π Python File Handling β Read, Write, Append & Manage Files Easily
π§² Introduction β Why File Handling Matters in Python
Handling files is essential for storing data permanently. Pythonβs built-in file handling functions make it easy to create, read, update, or delete filesβsupporting everything from configuration files and logs to data pipelines.
π― What You Will Learn:
- Opening, reading, and writing files using
open() - File modes:
r,w,a,x,b,t, and+ - Functions like
read(),write(),readlines(),writelines() - Exception handling with
try...exceptfor file errors
π 1. Opening and Closing Files
β
Using open() Function
file = open("example.txt", "r")
print(file.read())
file.close()
β Explanation:
"r"opens the file in read mode.close()frees system resources and ensures changes are saved.
π‘ Tip: Always close files manually or use a with block for auto-closure.
β
Using with Statement (Best Practice)
with open("example.txt", "r") as file:
content = file.read()
print(content)
β This ensures the file is closed automatically after the block ends.
π§Ύ 2. File Modes in Python
| Mode | Description |
|---|---|
'r' | Read mode (default). Errors if file doesn’t exist |
'w' | Write mode. Overwrites or creates new file |
'a' | Append mode. Adds to existing file or creates new |
'x' | Create mode. Fails if file exists |
'b' | Binary mode (e.g., images) |
't' | Text mode (default) |
'+' | Read and write combined (e.g., r+, w+) |
π 3. Reading from Files
β
read()
with open("example.txt", "r") as f:
print(f.read())
β Reads entire file content as a string.
β
readline()
with open("example.txt", "r") as f:
print(f.readline())
β Reads one line at a time.
β
readlines()
with open("example.txt", "r") as f:
lines = f.readlines()
print(lines)
β Returns a list of lines in the file.
βοΈ 4. Writing to Files
β
write()
with open("output.txt", "w") as f:
f.write("Hello, World!\n")
β
Writes a string to file. Must add \n for line breaks.
β
writelines()
lines = ["Line 1\n", "Line 2\n"]
with open("output.txt", "w") as f:
f.writelines(lines)
β Writes multiple strings (as list) into file.
β 5. Appending to Files
with open("output.txt", "a") as f:
f.write("New Line\n")
β Adds content at the end without overwriting existing data.
β 6. Handling File Not Found Errors
try:
with open("missing.txt", "r") as f:
print(f.read())
except FileNotFoundError:
print("File does not exist.")
β
Prevents crash if file is missing by using try...except.
π‘ Best Practices
- β
Use
with open()for safety and simplicity. - β
Choose correct file mode (
'r','w','a') as per operation. - β
Use
os.path.exists()to check file presence (optional). - β Handle exceptions gracefully.
π Summary β Recap & Next Steps
Python file handling is crucial for working with persistent data sources. From reading logs to writing reports, it simplifies data access and manipulation.
π Key Takeaways:
- Use
open()with correct modes (r,w,a,x) - Use
read(),write(),readlines()for I/O - Always use
with open()to manage files efficiently - Handle file-related errors with
try...except
βοΈ Real-World Relevance:
This is widely used in data logging, report generation, configuration management, and automation.
β FAQ β Python File Handling
β How do I safely open and close a file in Python?
β Use:
with open("file.txt", "r") as f:
print(f.read())
This auto-closes the file.
β Whatβs the difference between w and a?
β
'w' overwrites the file; 'a' appends data at the end.
β How do I read a file line by line?
β
Use readline() or a loop:
with open("file.txt", "r") as f:
for line in f:
print(line)β How to handle missing file errors?
β
Use try...except FileNotFoundError block.
β What’s the difference between text and binary mode?
β
't' is for human-readable text. 'b' is for non-text files like images or audio.
Share Now :
