Comprehensive Guide to Python File Input/Output (I/O)
1. Introduction to File Handling in Python
File handling is an essential part of programming. Python provides built-in functions to read, write,
and manipulate files efficiently.
2. Opening and Closing Files
Python's `open()` function is used to open files. The basic syntax is:
file = open("filename", "mode")
Example:
file = open("example.txt", "r")
file.close()
Using `with` statement (recommended):
with open("example.txt", "r") as file:
data = file.read()
3. File Modes in Python
- `r` : Read mode (default, file must exist).
- `w` : Write mode (creates a new file or overwrites).
- `a` : Append mode (adds data without deleting existing content).
- `r+` : Read and write.
- `w+` : Write and read (overwrites file).
- `a+` : Append and read.
- `rb`, `wb`, `ab` : Binary mode.
4. Reading Files
Methods for reading files:
- `read()`: Reads the entire file.
- `readline()`: Reads one line at a time.
- `readlines()`: Reads all lines as a list.
Example:
with open("example.txt", "r") as file:
content = file.read()
print(content)
5. Writing to Files
Methods for writing files:
- `write()`: Writes a string to the file.
- `writelines()`: Writes multiple lines.
Example:
with open("example.txt", "w") as file:
file.write("Hello, World!\n")
Appending:
with open("example.txt", "a") as file:
file.write("Appending new data.")
6. Working with CSV Files
Python has a built-in `csv` module to handle CSV files.
Reading CSV:
import csv
with open("data.csv", "r") as file:
reader = csv.reader(file)
for row in reader:
print(row)
Writing CSV:
with open("data.csv", "w", newline='') as file:
writer = csv.writer(file)
writer.writerow(["Name", "Age"])
writer.writerow(["Alice", 25])
7. Working with JSON Files
Python's `json` module helps read/write JSON data.
Writing JSON:
import json
data = {"name": "Alice", "age": 25}
with open("data.json", "w") as file:
json.dump(data, file)
Reading JSON:
with open("data.json", "r") as file:
data = json.load(file)
print(data)
8. Exception Handling in File I/O
Handling errors while working with files:
try:
with open("nonexistent.txt", "r") as file:
content = file.read()
except FileNotFoundError:
print("File not found!")
9. Reading Large Files Efficiently
For large files, reading line-by-line prevents memory overload:
with open("large_file.txt", "r") as file:
for line in file:
print(line, end="")