文件读写
有关文件和目录路径操作的更深入了解,请参阅 文件和目录路径 页面。
文件读写过程
要在 Python 中读/写文件,您应该使用 with 语句,它会在您完成后自动关闭文件,为您管理可用资源。
打开和读取文件
open 函数打开一个文件并返回一个相应的文件对象。
# 使用 'with' 语句读取文件:完成后自动关闭文件
with open('/home/labex/project/hi.txt') as hello_file:
hello_content = hello_file.read() # 读取整个文件内容
hello_content
'Hello World!'
测验
登录后即可答题并追踪学习进度
使用
with 语句打开文件的主要优点是什么?A. 完成后文件会自动关闭,即使发生错误
B. 文件打开速度更快
C. 文件可以同时以读写模式打开
D. 文件会自动压缩
或者,您可以使用 readlines() 方法从文件中获取字符串值列表,文件中的每一行对应一个字符串:
# readlines() 方法:返回字符串列表,每行一个字符串
with open('sonnet29.txt') as sonnet_file:
sonnet_file.readlines() # 返回一个列表,其中每行都是一个字符串
['When, in disgrace with fortune and men's eyes,\n',
' I all alone beweep my outcast state,\n',
"And trouble deaf heaven with my bootless cries,\n",
"And look upon myself and curse my fate,']
您也可以逐行迭代文件:
# 逐行迭代文件(对大文件更节省内存)
with open('sonnet29.txt') as sonnet_file:
for line in sonnet_file: # 文件对象是可迭代的
print(line, end='') # 打印时不加额外换行
When, in disgrace with fortune and men's eyes,
I all alone beweep my outcast state,
And trouble deaf heaven with my bootless cries,
And look upon myself and curse my fate,
写入文件
# 写入文件:'w' 模式会覆盖现有文件
with open('bacon.txt', 'w') as bacon_file: # 'w' = 写入模式
bacon_file.write('Hello world!\n') # 返回写入的字符数
13
# 追加到文件:'a' 模式会追加到现有文件
with open('bacon.txt', 'a') as bacon_file: # 'a' = 追加模式
bacon_file.write('Bacon is not a vegetable.')
25
with open('bacon.txt') as bacon_file:
content = bacon_file.read()
print(content)
Hello world!
Bacon is not a vegetable.
测验
登录后即可答题并追踪学习进度
打开文件时,模式
'w' 和模式 'a' 有什么区别?A.
'w' 用于读取,'a' 用于写入B.
'w' 覆盖文件,'a' 追加到文件C.
'w' 用于 Windows,'a' 用于 AppleD. 没有区别