文件是使用计算机的重要组成部分,因此使用Python写入和读取文件是需要掌握的基本技能。
1. 如何在Python中打开文件
open() 返回一个 file object :
open(file, mode='r', buffering=- 1, encoding=None, errors=None, newline=None, closefd=True, opener=None)
最常使用的是两个位置参数和一个关键字参数:open(filename, mode, encoding=None)
f = open('workfile', 'w', encoding="utf-8")
文件模式(mode)
第一个实参是文件名字符串。第二个实参是包含描述文件使用方式字符的字符串。mode
的值包括'r'
,表示文件只能读取;'w'
表示只能写入(现有同名文件会被覆盖);'a'
表示打开文件并追加内容,任何写入的数据会自动添加到文件末尾。'r+'
表示打开文件进行读写。mode
实参是可选的,省略时的默认值为'r'
。
通常情况下,文件是以text mode
打开的,也就是说,你从文件中读写字符串,这些字符串是以特定的 encoding
编码的。如果没有指定 encoding
,默认的是与平台有关的(见 open()
)。因为 UTF-8
是现代事实上的标准,除非你知道你需要使用一个不同的编码,否则建议使用 encoding="utf-8"
。在模式后面加上一个 'b'
,可以用 binary mode
打开文件。二进制模式的数据是以 bytes
对象的形式读写的。在二进制模式下打开文件时,你不能指定encoding
。
在文本模式下读取文件时,默认把平台特定的行结束符(Unix 上为\n
, Windows 上为\r\n
)转换为 \n
。在文本模式下写入数据时,默认把 \n
转换回平台特定结束符。这种操作方式在后台修改文件数据对文本文件来说没有问题,但会破坏 JPEG
或 EXE
等二进制文件中的数据。注意,在读写此类文件时,一定要使用二进制模式。
在处理文件对象时,最好使用with
关键字。优点是,子句体结束后,文件会正确关闭,即便触发异常也可以。而且,使用with
相比等效的try-finally
代码块要简短得多:
# 打开文件进行读取
with open('test.txt','r',encoding= 'utf-8') as file:
content = file.read()
print(content)
# 逐行进行读取
with open('test.txt','r',encoding='utf-8') as file:
for line in file:
print(line,end='')
# 读取指定字节数
with open('test.txt','r',encoding='utf-8') as file:
content = file.read(10)
print(content)
如果没有使用 with
关键字,则应调用f.close()
关闭文件,即可释放文件占用的系统资源。
警告 调用f.write()
时,未使用 with
关键字,或未调用f.close()
,即使程序正常退出,也可能
导致f.write()
的参数没有完全写入磁盘。
通过with
语句,或调用 f.close()
关闭文件对象后,再次使用该文件对象将会失败。
2. 写入文件
1)首先,需要确定文件模式。对照上面模式表格,需要使用’w’,‘t’。由于’t’是默认值,可以省略。
2)接下来,打开文件进行写入。
3)在文件对象上调用write()方法。
# 打开文件进行写入,如果文件不存在则创建
with open('text.txt','w',encoding='utf-8') as file:
file.write('Python学习ha\n')
# 追加内容到文件末尾
with open('text.txt','a',encoding='utf-8') as file:
file.write('3.1415926')
# 写入多行内容
lines = ['第一行:Python\n','第二行:Java\n','第三行:go\n']
with open('text.txt','w',encoding='utf-8') as file:
file.writelines(lines)
3. file对象的方法
# 打开文件并获取当前文件指针位置
with open('example.txt', 'r') as file:
position = file.tell()
print(f"Current position: {position}")
# 打开文件并移动文件指针
with open('example.txt', 'r') as file:
file.seek(5) # 移动文件指针到第5个字节
content = file.read()
print(content)
# 打开文件进行写入,然后刷新缓冲区
with open('example.txt', 'w') as file:
file.write('Hello, World!')
file.flush() # 刷新缓冲区,确保数据被写入文件
# 打开文件进行截断
with open('example.txt', 'r+') as file:
file.seek(5) # 移动文件指针到第5个字节
file.truncate() # 截断文件到当前文件指针位置
4. 参考
官网:
https://docs.python.org/zh-cn/3/tutorial/inputoutput.html#methods-of-file-objects
菜鸟教程:
https://www.runoob.com/python3/python3-file-methods.html