I have two Python processes A
and B
and both are trying to write to the same file. After A
has reached f = open("xx.txt", "w")
and before it closes the file, I hope the other process has a way to detect that xx.txt
is in use.
I've tried f = open("xx.txt", "w")
in process B
but it didn't throw any exception. I've also tried os.access("xx.txt", os.W_OK)
in B
, it returns True
.
I know that I can use some file lock library such as lockfile or fcntl.But I am wondering if there is any simple solution without relying on these libs for me to detect it?
EDIT: I found a possible solution:
use os.open to open the file:
open_flags = (os.O_CREAT | os.O_EXCL | os.O_WRONLY)
fd = os.open( "xx.txt", open_flags )
And we can get exception if the file already exists:
open_flags = (os.O_CREAT | os.O_EXCL | os.O_WRONLY)
>>> fd = os.open( "xx.txt", open_flags )
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
OSError: [Errno 17] File exists: 'xx.txt'