Check if a File is written or in use by another process

Viewed 576

I try to find a solution for the following problems but can't find any good solution. I have a folder with subfolder and files in it. Some of the files may be in use by another process (the other process is writing data to the data (a .mdf file)).

I simply want to check if the files are in use or not.

Structure:

A_Folder
  Setup
  Data1
    .mdf-file1
    .mdf-file2
  Data2
  Data3
  Evaluation

something like:

def file_in_use():
    *your solution*

for file in folder:
    if file_in_use(file):
        print("file in use")
        break

I'm Using Win10, PyCharm and a venv.

I tried so far form other "solutions":

  • psutil (works, but is too slow)
  • open(), os.rename - won't work for me
  • subprocess wont work either -cant find my filename: using the method from Amit Gupta from my link down below, file looks like this: "C:\Data\S_t_h\S-t-h\H001.mdf"

basically I tried everything from this question:

Check if a file is not open nor being used by another process

from subprocess import check_output, Popen, PIPE

src = r"C:\Data\S_t_h\S-t-h\H001.mdf"
files_in_use = False


def file_in_use(src):

    try:
        lsout = Popen(['lsof', src], stdout=PIPE, shell=False)
        check_output(["grep", src], stdin=lsout.stdout, shell=False)
    except:
        return False

return True


if file_in_use(src):
    files_in_use = True

and im getting: FileNotFoundError: [WinError 2] The system cannot find the file specified

this link suggesting setting

winerror-2-the-system-cannot-find-the-file-specified-python

shell=True

Im getting "lsof" and "grep" cant be found or are wrong now.

Here the psutil method that works for me, but is too slow (~10 Seconds)

import psutil

src = r"C:\Data\S_t_h\S-t-h\H001.mdf"

def has_handle(src):
    for proc in psutil.process_iter():
        try:
            for item in proc.open_files():
                if src == item.path:
                    return True
        except Exception:
            pass

    return False


 print(has_handle(src))

My Solution:

Sorry for the delayed answer. It simply worked with:

    try:
        os.rename(src, src)
        return False
    except OSError:    # file is in use
        return True

I made it more complicated than it actually was i guess. But thank you guys anyway for your feedback and critizism.

0 Answers
Related