1

I have a task, I wanna check if exist special file *.part in directory. If file exist do check again, if not, print "file was deleted".

I use os.listdir(), next for each file in lisdir, I use fnmatch(file, '*.part'),next again get lisdir and recursively involve same function.

When I'am deleting this file, fnmatch return "true". I can't understand... "why"?

Here my code:

import os, fnmatch

def func(filenames):
      for f in filenames:
            while fnmatch.fnmatch(f, '*.part'):
                  filenames = os.listdir("/home/gromov/Downloads/test/")
                  func(filenames)


if __name__ == "__main__":
      func(os.listdir("/home/gromov/Downloads/test/"))
      print("file was deleted")

Thanks!

fish2000
  • 4,289
  • 2
  • 37
  • 76

2 Answers2

1

You are using recursion, perhaps the list of files you get from os.listdir() returns the same files list every time and therefor you get a True returned before it is updated.

Try writing this in a none recursive way and make sure the list you retrieve from os.listdir() is not the same every iteration you do.

N.P
  • 64
  • 4
  • I get new list intro "while" and pass his in func(), and in debug i see that it's new list, but in for loop " f " again become last value. – Pavel Gromov Dec 28 '16 at 12:50
1

Even if you call your function func recursively, f in the first iteration never changes and fnmatch only checks the string and not, if the file exists.

Use os.path.exists: import os, fnmatch, time

def func(filenames):
    for f in filenames:
        if fnmatch.fnmatch(f, '*.part'):
            # wait until deleted
            while os.path.exists(f):
                time.sleep(0.1)
Daniel
  • 42,087
  • 4
  • 55
  • 81