Should I close a file before moving it?

前端 未结 3 1813
小鲜肉
小鲜肉 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 18:57

    On Windows:

    >>> import os
    >>> with open('old.txt') as file:
            os.rename('old.txt', 'new.txt')
    
    Traceback (most recent call last):
      File "", line 2, in 
        os.rename('test.txt', 'newtest.txt')
    WindowsError: [Error 32] The process cannot access the file because it is being used by another process
    

    You can't move the file, because someone(you) is already holding it. You need to close the file before you can move it.

提交回复
热议问题