2016-11-11 56 views

回答

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 
0

總之,使用with open(filename, mode) as file:是更有效,因爲你可以擺脫file.close()

相關問題