In Python programming, file I/O operations are common tasks. This article will introduce some common problems and solutions about Python file I/O operations, and provide detailed code examples.
1. Question: How to open and close files correctly?
Solution: Use with
statements to ensure that the file is automatically closed after the operation is completed to avoid resource leaks.
with open("example.txt", "r") as file:
content = file.read()
2. Question: How to read a file line by line?
Solution: Use for
a loop to iterate over the file object, reading line by line.
with open("example.txt", "r") as file:
for line in file:
print(line.strip())
3. Question: How to deal with file encoding issues?
Solution: Use a parameter to specify the file encoding when opening the file encoding
.
with open("example.txt", "r", encoding="utf-8") as file:
content = file.read()
4. Question: How to find specific content in a file?
Solution: Read the file line by line, using string methods like find
or in
to check if each line contains the target content.
target = "Python"
with open("example.txt", "r") as file:
for line_number, line in enumerate(file, start=1):
if target in line:
print(f"Found '{
target}' at line {
line_number}")
5. Question: How to deal with large files?
Solution: Use a generator function to read the file chunk by chunk to avoid loading the entire file at once.
def read_large_file(file_path, block_size=1024):
with open(file_path, "r") as file:
while True:
data = file.read(block_size)
if not data:
break
yield data
for chunk in read_large_file("large_file.txt"):
process(chunk)
6. Question: How to read and write CSV files?
Solution: Use Python’s built-in csv
modules to process CSV files.
import csv
# 读取CSV文件
with open("example.csv", "r") as file:
reader = csv.reader(file)
for row in reader:
print(row)
# 写入CSV文件
data = [["Name", "Age"], ["Alice", 30], ["Bob", 25]]
with open("output.csv", "w", newline="") as file:
writer = csv.writer(file)
writer.writerows(data)
7. Question: How to read and write JSON files?
Solution: Use Python’s built-in json
modules to process JSON files.
import json
# 读取JSON文件
with open("example.json", "r") as file:
data = json.load(file)
# 写入JSON文件
data = {
"name": "Alice", "age": 30}
with open("output.json", "w") as file:
json.dump(data, file)
File I/O operations in Python involve many common issues. When writing code, paying attention to these problems and their solutions will help improve the robustness and maintainability of the program.