Skip to content Skip to sidebar Skip to footer

Should I Close A File Before Moving It?

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... Are there any problems with tha

Solution 1:

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.

Solution 2:

On 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

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

Solution 3:

Best practice with file is close and move, because if you will not close then it might be create problem in some OS, like Windows.

To make your code more portable, close file before move.

Post a Comment for "Should I Close A File Before Moving It?"