check if a file is open in Python
I assume that you're writing to the file, then closing it (so the user can open it in Excel), and then, before re-opening it for append/write operations, you want to check that the file isn't still open in Excel?
This is how you could do that:
while True: # repeat until the try statement succeeds
try:
myfile = open("myfile.csv", "r+") # or "a+", whatever you need
break # exit the loop
except IOError:
input("Could not open file! Please close Excel. Press Enter to retry.")
# restart the loop
with myfile:
do_stuff()
How to check if a file is already opened (in the same process)
You should open the same file but assign them to different variables, like so:
file_obj = open(filename, "wb+")
if not file_obj.closed:
print("File is already opened")
The .closed
only checks if the file has been opened by the same Python process.
Check if a file is not open nor being used by another process
An issue with trying to find out if a file is being used by another process is the possibility of a race condition. You could check a file, decide that it is not in use, then just before you open it another process (or thread) leaps in and grabs it (or even deletes it).
Ok, let's say you decide to live with that possibility and hope it does not occur. To check files in use by other processes is operating system dependant.
On Linux it is fairly easy, just iterate through the PIDs in /proc. Here is a generator that iterates over files in use for a specific PID:
def iterate_fds(pid):
dir = '/proc/'+str(pid)+'/fd'
if not os.access(dir,os.R_OK|os.X_OK): return
for fds in os.listdir(dir):
for fd in fds:
full_name = os.path.join(dir, fd)
try:
file = os.readlink(full_name)
if file == '/dev/null' or \
re.match(r'pipe:\[\d+\]',file) or \
re.match(r'socket:\[\d+\]',file):
file = None
except OSError as err:
if err.errno == 2:
file = None
else:
raise(err)
yield (fd,file)
On Windows it is not quite so straightforward, the APIs are not published. There is a sysinternals tool (handle.exe
) that can be used, but I recommend the PyPi module psutil
, which is portable (i.e., it runs on Linux as well, and probably on other OS):
import psutil
for proc in psutil.process_iter():
try:
# this returns the list of opened files by the current process
flist = proc.open_files()
if flist:
print(proc.pid,proc.name)
for nt in flist:
print("\t",nt.path)
# This catches a race condition where a process ends
# before we can examine its files
except psutil.NoSuchProcess as err:
print("****",err)
How to check if a file is closed?
Your AttributeError seems to say that you should execute .close() on the file handle instead oft the path string.
closeXl = r"C:\Users\R\Downloads\Chat.xls"
file = open(closeX1)
if not file.closed:
file.close()
In most cases it would be a better solution would be to use the with-statement. It closes the file automatically at the end of the block.
closeXl = r"C:\Users\R\Downloads\Chat.xls"
with open(closeX1) as file:
pass # your code here
If you want to check if a file is opened read-write from another process and therefore locked, you should have a look at:
https://www.calazan.com/how-to-check-if-a-file-is-locked-in-python/
Check if a file is still open in python
Maybe you would prefer to use the context manager version:
with open(file_path, 'r') as f:
# do something with f
# f is closed now
This is closing the file automatically for you.
Edit:
It seems the OP wants to launch Windows paint with an image that has been (somehow) detected to need some user editing.
An alternative to achieve this would be: while looping through the images make a simple call to:
path_to_image = <image_file_path_here>
os.system(f'mspaint {path_to_image }')
this will open Paint with the desired image and the program will only continue execution once the Paint window is closed.
How to check whether a file is_open and the open_status in python
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"
if not os.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)
Related Topics
How to Break a Long Line to Multiple Lines in Python
Accessing Object Memory Address
Opencv Real Time Streaming Video Capture Is Slow. How to Drop Frames or Get Synced with Real Time
Accessing Every 1St Element of Pandas Dataframe Column Containing Lists
Pyplot Common Axes Labels for Subplots
Python Eval: Is It Still Dangerous If I Disable Builtins and Attribute Access
Cannot Install Python 3.7 on Osx-Arm64
A Tool to Convert Matlab Code to Python
How to Manage Third-Party Python Libraries with Google App Engine? (Virtualenv? Pip)
How to Run Scrapy from Within a Python Script
How to Request a Url in Python and Not Follow Redirects
Where to Put Freeze_Support() in a Python Script
Query for List of Attribute Instead of Tuples in SQLalchemy