Python: opening a file without creating a lock

I am trying to create a script in Python to back up some files. But these files could be renamed or deleted at any time. I do not want my script to prevent this by locking the file; the file should be able to still be deleted at any time during the backup.

How can I do this in Python? And what is going on? Do my objects just become empty if the stream cannot be read?

Thanks! I am a little new to Python.

+4
source share
2 answers

As already mentioned, this is a problem with Windows. Unix OS allow you to delete.

To do this on Windows, I needed to use win32file.CreateFile to use the dwSharingMode flag defined in Windows (in Python win32file, it is simply called "sharemode"). Here are some documents on it: http://docs.activestate.com/activepython/2.7/pywin32/win32file__CreateFile_meth.html

A rough example:

import win32file # Ensure you import the module. file_handle = win32file.CreateFile('filename.txt', win32file.GENERIC_READ, win32file.FILE_SHARE_DELETE | win32file.FILE_SHARE_READ | win32file.FILE_SHARE_WRITE, None, win32file.OPEN_EXISTING, win32file.FILE_ATTRIBUTE_NORMAL, None) 
+5
source

On UNIX-like operating systems, including Linux, this is not a problem. Well, another program can write to a file at the same time as reading, which can cause problems (the file you are copying may be corrupted), but this can be resolved using a test pass.

On Windows, use the snapshot service (for example, shadow copying a volume). VSS takes a snapshot of the volume at a point in time, and you can open files in the snapshot without locking the files on the original volume. Quick Google found a module for copying using VSS for Python here: http://sourceforge.net/projects/pyvss/

+4
source

All Articles