在Python中,文件读写主要通过内置的open()函数实现。
open()函数接受两个参数:文件名和模式。模式可以是以下之一:
‘r’:只读模式(默认)
‘w’:写入模式,如果文件不存在则创建,如果存在则覆盖
‘a’:追加模式,如果文件不存在则创建,如果存在则在文件末尾追加内容
‘x’:创建模式,如果文件不存在则创建,如果存在则报错
‘b’:二进制模式,与其他模式结合使用,如’rb’、‘wb’、‘ab’、‘xb’
‘t’:文本模式(默认),与其他模式结合使用,如’rt’、‘wt’、‘at’、‘xt’
以下是一些常见的文件读写操作:
# 1.读取文件内容
with open('file.txt', 'r') as f:
content = f.read()
print(content)
# 2.写入文件内容
with open('file.txt', 'w') as f:
f.write('Hello, World!')
# 3.追加文件内容
with open('file.txt', 'a') as f:
f.write('Hello, again!')
# 4.读取文件每一行
with open('file.txt', 'r') as f:
for line in f:
print(line.strip())
# 5.写入文件多行内容
with open('file.txt', 'w') as f:
f.writelines(['Line 1', 'Line 2', 'Line 3'])
# 6.读取文件指定范围的内容
with open('file.txt', 'r') as f:
content = f.readlines()[1:4] # 读取第2行到第4行
print(content)
# 7.指定范围的内容写入文件
with open('file.txt', 'w') as f:
# 将第2行到第4行写入文件
f.writelines(['Line 1', 'Line 2', 'Line 3', 'Line 4', 'Line 5'][1:4])