Should I close a file before moving it?

前端 未结 3 1727
小鲜肉
小鲜肉 2021-01-20 18:23

I have code like this:

with open(\'foo.txt\') as file:
    ...do something with file...
    ...move foo.txt to another place while it\'s still open...
         


        
3条回答
  •  被撕碎了的回忆
    2021-01-20 19:13

    This depends on the operating system. In Unix-based systems this is generally safe (you can move or even delete file while still having it open). Windows will produce Access Denied error if you try to move/delete an opened file.

    So yes, the safest and portable way is to close the file first. Note that with clause closes the file automatically, so all you need is to perform the move outside of with block.

提交回复
热议问题