我有这样的代码:
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)
这有什么问题吗?
这取决于操作系统.在基于Unix的系统中,这通常是安全的(您可以移动甚至删除文件,同时仍然打开它).如果您尝试移动/删除打开的文件,Windows将生成"拒绝访问"错误.
所以是的,最安全和最便携的方法是先关闭文件.请注意,with条款自动关闭文件,因此,所有你需要的是执行移动以外的with块.
| 归档时间: |
|
| 查看次数: |
99 次 |
| 最近记录: |