为何使用Python的'a+'读写模式无法读取文件内容?
问题描述
使用Python的a+模式操作文件时,执行以下代码无任何输出:
handler = open('test.txt', 'a+') for idx, line in enumerate(handler): print(idx, line.strip())
但将模式改为r+后,能正常打印文件内容:
0 a test 1 two test
test.txt的原始内容为:
a test two test
需求是打开文件后既能读取内容,又能在文件末尾追加新内容,请问a+模式为何无法正常工作?
原因分析
a+模式的核心特性是:打开文件后,文件指针默认定位在文件末尾。此时直接执行读取操作,相当于从文件末尾开始读取,自然获取不到任何内容。而r+模式打开文件时,指针默认处于文件开头,所以能直接读取到文件内容。
解决方案
要实现既能读取又能追加的需求,只需在打开文件后,先调用seek(0)将文件指针移到开头,读取完成后指针会自动回到文件末尾,此时直接写入内容就会追加到文件最后:
handler = open('test.txt', 'a+') # 将指针移到文件开头,准备读取内容 handler.seek(0) for idx, line in enumerate(handler): print(idx, line.strip()) # 指针已回到末尾,直接写入即为追加操作 handler.write('new line\n') handler.close()
更推荐使用with语句自动管理文件句柄,避免手动关闭遗漏:
with open('test.txt', 'a+') as handler: handler.seek(0) for idx, line in enumerate(handler): print(idx, line.strip()) handler.write('another new line\n')
内容的提问来源于stack exchange,提问作者marlon
相关产品推荐
相关产品推荐

