我有这样的代码:
with open('foo.txt') as file:
...do something with file...
...move foo.txt to another place while it's still open...
这有什么问题吗?
答案 0 :(得分:6)
这取决于操作系统。在基于Unix的系统中,这通常是安全的(您可以移动甚至删除文件,同时仍然打开它)。如果您尝试移动/删除打开的文件,Windows将产生“拒绝访问”错误。
所以是的,最安全和最便携的方法是先关闭文件。请注意,with
子句会自动关闭文件,因此您只需执行with
块 的移动
答案 1 :(得分:4)
在Windows上:
>>> import os
>>> with open('old.txt') as file:
os.rename('old.txt', 'new.txt')
Traceback (most recent call last):
File "<pyshell#4>", line 2, in <module>
os.rename('test.txt', 'newtest.txt')
WindowsError: [Error 32] The process cannot access the file because it is being used by another process
您无法移动文件,因为有人(您)已经拥有该文件。您需要在移动文件之前关闭该文件。
答案 2 :(得分:0)
file
的最佳做法是close
和move
,因为如果您不close
,那么在某些操作系统中可能会出现问题,例如Windows
。
为了使您的代码更具可移植性,请close
之前提交move
文件。