Python 文件操作:读写与处理
一、文件打开与关闭
(一)open() 函数
在 Python 里,open() 函数用于打开文件,其基本语法为:
file_object = open(file_path, mode)
file_path:指的是文件的路径,可以是绝对路径,也可以是相对路径。mode:表示文件的打开模式,常见模式如下:'r':以只读模式打开文件,文件指针置于文件开头,若文件不存在则报错。'w':以写入模式打开文件,若文件存在则清空内容,若文件不存在则创建新文件。'a':以追加模式打开文件,文件指针置于文件末尾,若文件不存在则创建新文件。'b':以二进制模式打开文件,可与其他模式组合,如'rb'表示以二进制只读模式打开。'+':可读写模式,可与其他模式组合,如'r+'表示以读写模式打开文件。
(二)文件关闭
使用完文件后,需调用 close() 方法关闭文件,以释放系统资源。示例如下:
file = open('example.txt', 'r')
# 对文件进行操作
file.close()
也可使用 with 语句来自动管理文件的打开和关闭,代码更简洁且安全:
with open('example.txt', 'r') as file:
# 对文件进行操作
pass
# 离开 with 语句块,文件自动关闭
二、文件读取
(一)read() 方法
read() 方法用于读取文件的全部内容或指定字节数的内容。示例如下:
with open('example.txt', 'r') as file:
content = file.read() # 读取文件全部内容
print(content)
file.seek(0) # 将文件指针移到文件开头
partial_content = file.read(10) # 读取前 10 个字符
print(partial_content)
(二)readline() 方法
readline() 方法用于逐行读取文件内容,每次调用会读取一行。示例如下:
with open('example.txt', 'r') as file:
line = file.readline()
while line:
print(line.strip()) # 去除行尾的换行符
line = file.readline()
(三)readlines() 方法
readlines() 方法会将文件的每一行作为一个元素,存储在列表中返回。示例如下:
with open('example.txt', 'r') as file:
lines = file.readlines()
for line in lines:
print(line.strip())
三、文件写入
(一)write() 方法
write() 方法用于向文件中写入字符串内容。示例如下:
with open('example.txt', 'w') as file:
file.write('Hello, World!\n')
file.write('This is a test.')
(二)writelines() 方法
writelines() 方法用于向文件中写入一个字符串列表,不会自动添加换行符。示例如下:
lines = ['Line 1\n', 'Line 2\n', 'Line 3']
with open('example.txt', 'w') as file:
file.writelines(lines)
四、文件追加
使用 'a' 模式打开文件可实现内容追加。示例如下:
with open('example.txt', 'a') as file:
file.write('\nThis is an appended line.')
五、文件指针操作
(一)seek() 方法
seek() 方法用于移动文件指针的位置,其语法为:
file.seek(offset, whence)
offset:表示偏移量,正数表示向后移动,负数表示向前移动。whence:指定偏移的参考位置,取值如下:0:从文件开头开始偏移(默认值)。1:从当前文件指针位置开始偏移。2:从文件末尾开始偏移。
示例如下:
with open('example.txt', 'r') as file:
file.seek(5, 0) # 从文件开头向后移动 5 个字符
content = file.read()
print(content)
(二)tell() 方法
tell() 方法用于返回文件指针当前的位置。示例如下:
with open('example.txt', 'r') as file:
position = file.tell()
print(f'当前文件指针位置: {position}')
file.read(10)
position = file.tell()
print(f'读取 10 个字符后文件指针位置: {position}')
六、文件处理实际应用
(一)文件复制
def copy_file(source_path, destination_path):
with open(source_path, 'r') as source_file:
content = source_file.read()
with open(destination_path, 'w') as dest_file:
dest_file.write(content)
copy_file('source.txt', 'destination.txt')
(二)统计文件行数
def count_lines(file_path):
with open(file_path, 'r') as file:
lines = file.readlines()
return len(lines)
line_count = count_lines('example.txt')
print(f'文件行数: {line_count}')
(三)文件内容替换
def replace_text(file_path, old_text, new_text):
with open(file_path, 'r') as file:
content = file.read()
new_content = content.replace(old_text, new_text)
with open(file_path, 'w') as file:
file.write(new_content)
replace_text('example.txt', 'old', 'new')