How To Check Whether A File Is_open And The Open_status In Python
Solution 1:
This is not quite what you want, since it just tests whether a given file is write-able. But in case it's helpful:
import os
filename = "a.txt"ifnotos.access(filename, os.W_OK):
print"Write access not permitted on %s" % filename
(I'm not aware of any platform-independent way to do what you ask)
Solution 2:
Here is an is_open solution for windows using ctypes:
from ctypes import cdll
_sopen = cdll.msvcrt._sopen
_close = cdll.msvcrt._close
_SH_DENYRW = 0x10defis_open(filename):
ifnot os.access(filename, os.F_OK):
returnFalse# file doesn't exist
h = _sopen(filename, 0, _SH_DENYRW, 0)
if h == 3:
_close(h)
returnFalse# file is not opened by anyone elsereturnTrue# file is already open
Solution 3:
I think the best way to do that is to try.
defis_already_opened_in_write_mode(filename)
if os.path.exists(filename):
try:
f = open(filename, 'a')
f.close()
except IOError:
returnTruereturnFalse
Solution 4:
There is a attribute to check the open status or mode of a file.
filename = open('open.txt','r')
print(filename.mode)
Python has an inbuilt attribute called 'mode'. Above code will return 'r'. Similarly if you open a file in 'w' mode above code will return 'w'
You can also check if a file is open or closed
print(filename.closed)
This will return 'FALSE' as the file is in open state.
filename.closedprint(filename.closed)
This will return 'TRUE' because the file is now in close state.
Thank you
Solution 5:
I don't think there is an easy way to do what you want, but a start could be to redefine open() and add your own managing code. That said, why do you want to do that?
Post a Comment for "How To Check Whether A File Is_open And The Open_status In Python"