- 1 year ago
Windows/Python check if file is open or in use
To check if a file is open or in use on Windows using Python, you can use the psutil
library. psutil
provides a cross-platform way to access system details and processes. Here's an example of how you can use psutil
to check if a file is open or in use:
pythonimport psutil
def is_file_open(file_path):
for process in psutil.process_iter(['pid', 'name', 'open_files']):
try:
for file in process.open_files():
if file.path == file_path:
return True
except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
pass
return False
# Usage
file_path = 'C:/path/to/file.txt'
if is_file_open(file_path):
print(f'The file "{file_path}" is open or in use.')
else:
print(f'The file "{file_path}" is not open or in use.')
In the code above, the is_file_open()
function takes a file path as an argument and iterates through the running processes using psutil.process_iter()
. It then checks each process's open files using the open_files()
method. If any open file path matches the input file path, it returns True
, indicating that the file is open or in use. If no matches are found, it returns False
.
Note that psutil
may require installation. You can install it using pip install psutil
.
By using the psutil
library, you can check if a file is open or in use on Windows from within your Python script.