Reputation: 40202
I would like to read/write to a file but allow for it to be deleted/renamed by other processes. In C#
you can open the file with a FileShare.Delete
, does Python have an equivalent?
Upvotes: 3
Views: 550
Reputation: 365915
If you want a cross-platform equivalent… there really isn't one. On POSIX systems, other processes can always delete/rename files you have open* unless you go out of your way to prevent it. So, you only need to do this for Windows, and you have it pretty much everywhere
Python's standard file objects don't allow you to control Windows sharing flags directly. (This is because they use cross-platform APIs like stdio's fopen
rather than the Windows-specific APIs.)
If you want to do this, you have to call different file functions.
In IronPython, you can of course call the exact same .NET functions you'd call in C#.
In CPython, you can't use .NET, because CPython is a native Win32 app. That means you have to call CreateFile
. You can use the pywin32 package to make this easier, but it's still a bit of a pain.
Instead of just f = open(path, 'r+')
, you need something like this (untested):
f = win32file.CreateFile(path,
win32con.GENERIC_READ | win32con.GENERIC_WRITE,
win32con.FILE_SHARE_DELETE,
None,
0,
win32con.OPEN_ALWAYS,
None)
And then, instead of buf = f.read(4096)
, you do:
buflen, buf = win32file.ReadFile(f, 4096, None)
And, instead of just sticking it in a with
statement, you have to explicitly close it, with:
win32file.CloseFile(f)
If you plan on doing a lot of this, wrapping up a win32file
handle in a file-like object isn't that hard, and is probably worth doing.
The trickiest bit is deciding how close you want to stick to the arguments for open
, and writing the code to convert the values you get into the ones CreateFile
wants. (There are also a few edge cases that Win32 native files handles differently than Win32 stdio files, but usually these won't bit you.)
You may also want to look at the io
module for helpers that let you just implement a handful of raw open/read/write/close functions and wrap it up in a complete file-like object automatically.
* Actually, all they can do is unlink the directory entry that you opened. Even if that was the only directory entry linking to that file, the file itself still exists until the last open handle to it is closed.
Upvotes: 6