check if a file is open in Python
While writing to the file, then close it , so conceited that the user can open it in file. So need to check that the file is not still open in Excel, before re-opening it for append/write operations.
Try this code :
try: myfile = open("myfile.csv", "r+") # or "a+", whatever you need except IOError: print "Could not open file! Please close Excel!" with myfile: do_stuff()
The best way is to use the file object attribute “closed”
Use this code :
f = open('file.py') if f.closed: print 'file is closed'
Try this useful link :
Here the solution for check if a file is open in Python :
The alternative way is rename the file or directory including the file temporarily, after this rename it back.
Follow this code :
import os try: os.rename('file.xls', 'tempfile.xls') os.rename('tempfile.xls', 'file.xls') except OSError: print('File is still open.')