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 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()
Is there a way I can check to see if the file is already open?
To use this code, you would use the function as in the following example:
Imports System.IO
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
If OpenUnlockedFile("C:\Data.xlsb") Is Nothing Then
MessageBox.Show("File is locked")
End If
End Sub
Public Shared Function OpenUnlockedFile(ByVal path As String) As StreamWriter
Dim sw As StreamWriter = Nothing
Try
sw = New StreamWriter(path)
Catch ex As IOException When System.Runtime.InteropServices.Marshal.GetLastWin32Error() = 32
REM locked, return nothing
End Try
Return sw
End Function
End Class
The function, OpenUnlockedFile("C:\Data.xlsb") is run whenever you press Button1 (in this example). If the function is run and it returns Nothing, then you will know the file is locked.
Please note that you will also need
Imports System.IO
for this example to work.
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 already open by another process in C?
There's no way tell, unless the other process explicitly forbids access to the file. In MSVC, you'd do so with _fsopen()
, specifying _SH_DENYRD
for the shflag argument. The notion of being interested whether a file is opened that isn't otherwise locked is deeply flawed on a multitasking operating system. It might be opened a microsecond after you'd have found it wasn't. That's also the reason that Windows doesn't have a IsFileLocked() function.
If you need synchronized access to files, you'll need to add this with a named mutex, use CreateMutex().
A way to know if the file currently is open before open it again?
It seems to me that your question has really nothing to do with file opening in the programmatic sense, but is exclusively related to your application logic. You need to internally keep a list of all currently open files (in the sense that your GUI is showing such file), and do a check if the user opens a new file.
Related Topics
How to Make the Division of 2 Ints Produce a Float Instead of Another Int
Why Integer Class Caching Values in the Range -128 to 127
Java 8: Difference Between Two Localdatetime in Multiple Units
Implementing Singleton with an Enum (In Java)
How to Maintain Jtable Cell Rendering After Cell Edit
Calling a Subclass Method from Superclass
How to Properly Override Clone Method
What Is the Native Keyword in Java For
Map Implementation with Duplicate Keys
What Is a "Surrogate Pair" in Java
Sqlexception: No Suitable Driver Found for Jdbc:Derby://Localhost:1527
How to Catch Multiple Java Exceptions in the Same Catch Clause
How to Implement the Java Comparable Interface
How to Convert a Hibernate Proxy to a Real Entity Object
Resize an Array While Keeping Current Elements in Java
How to Find the Duration of Difference Between Two Dates in Java