我应该在移动之前关闭文件吗?

Mir*_*rak 3 python

我有这样的代码:

with open('foo.txt') as file:
    ...do something with file...
    ...move foo.txt to another place while it's still open...
Run Code Online (Sandbox Code Playgroud)

这有什么问题吗?

ham*_*ene 6

这取决于操作系统.在基于Unix的系统中,这通常是安全的(您可以移动甚至删除文件,同时仍然打开它).如果您尝试移动/删除打开的文件,Windows将生成"拒绝访问"错误.

所以是的,最安全和最便携的方法是先关闭文件.请注意,with条款自动关闭文件,因此,所有你需要的是执行移动以外with块.