Comprehensive Guide to File Operations in Python
This article provides a thorough introduction to Python file operations, covering basic concepts, opening and closing files, reading and writing techniques, advanced methods like binary handling and file pointer control, and includes practical code examples and best‑practice recommendations.
In Python programming, file operations are essential for handling text data, storing user information, and reading configuration files.
Table of Contents
Basic concepts of file operations
Opening and closing files
Reading file content
Writing file content
Advanced file operation techniques
Summary and suggestions
Basic concepts of file operations
Python file handling typically involves three steps: opening a file with open() , reading or writing data, and closing the file with close() . Both text and binary files are supported.
Opening and closing files
Scenario 1 – manual open and close:
file = open("example.txt", "r", encoding="utf-8") # open for reading
content = file.read() # read content
print("文件内容:", content)
file.close() # close fileScenario 2 – using a with statement for automatic closing:
with open("example.txt", "r", encoding="utf-8") as file:
content = file.read()
print("文件内容:", content)
# file is automatically closed hereReading file content
Scenario 3 – line‑by‑line reading with readline() or readlines() :
with open("example.txt", "r", encoding="utf-8") as file:
lines = file.readlines()
for line in lines:
print("读取的行:", line.strip())Scenario 4 – iterating over the file object directly:
with open("example.txt", "r", encoding="utf-8") as file:
for line in file:
print("读取的行:", line.strip())Writing file content
Scenario 5 – writing text to a file:
with open("output.txt", "w", encoding="utf-8") as file:
file.write("这是第一行内容。\n")
file.write("这是第二行内容。\n")
print("写入完成!")Scenario 6 – appending to an existing file:
with open("output.txt", "a", encoding="utf-8") as file:
file.write("这是追加的内容。\n")
print("追加完成!")Advanced techniques
Scenario 7 – reading a specific number of characters:
with open("example.txt", "r", encoding="utf-8") as file:
first_10_chars = file.read(10)
print("读取的前10个字符:", first_10_chars)Scenario 8 – copying a binary file (e.g., an image):
with open("example.jpg", "rb") as source:
with open("copy_example.jpg", "wb") as target:
target.write(source.read())
print("图片复制完成!")Scenario 9 – using seek() and tell() to control the file pointer:
with open("example.txt", "r", encoding="utf-8") as file:
print("当前指针位置:", file.tell())
file.seek(10) # move to the 10th character
print("移动后读取的内容:", file.read(5))Scenario 10 – managing files and directories with os and shutil :
import os
import shutil
os.mkdir("test_dir") # create directory
shutil.copy("example.txt", "test_dir/copy_example.txt") # copy file
os.remove("test_dir/copy_example.txt") # delete file
os.rmdir("test_dir") # remove empty directory
print("文件和目录操作完成!")Summary and suggestions
Always use a with statement to ensure files are closed properly.
Choose the appropriate mode ( r , w , a , rb , wb ) based on the task.
Specify encoding="utf-8" for text files to avoid encoding errors.
Use binary modes for non‑text files such as images or audio.
Control the file pointer with seek() and tell() when precise positioning is needed.
Leverage os and shutil for directory and file management.
Mastering these file‑handling techniques will make your Python code more efficient and robust.
Test Development Learning Exchange
Test Development Learning Exchange
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.