如何在写入时打开文件,关闭它,然后在读取时重新打开?

时间:2016-11-11 02:56:08

标签: file python-3.x

我目前正在为学校编写代码,在关闭文件后重新打开文件时遇到问题。

test=open('test.txt','w')
.......
test.close

retest=open('test.txt','r')

这是我收到的确切错误消息:

TypeError: invalid file: <_io.TextIOWrapper name='test.txt' 
         mode='w' encoding='cp1252'>

2 个答案:

答案 0 :(得分:1)

您需要使用test.close()关闭该文件。如果没有(),则test.close未被调用,仅被引用,并且当您尝试重新打开文件时,您的文件仍处于打开状态。

更好的是,您可以使用上下文管理器,您的文件将自动关闭:

with open('test.txt', 'w') as test:
    ...
with open('test.txt', 'r') as retest:
    ...

或者更好(取决于您的使用案例),您可以使用r+模式打开文件以同时阅读

with open('test.txt', 'r+') as test:
    # read and write to file as necessary

答案 1 :(得分:0)

无论如何,使用with open(filename, mode) as file:更有效率,因为你可以摆脱file.close()