3

I would like to search files, except those which contain .txt file. How to do that ? At the moment my code is searching for files with .txt extension on it. How to do an opposite?

src = raw_input("Enter source disk location: ")
src = os.path.abspath(src)
print "src--->:",src
for dir,dirs,_ in os.walk(src, topdown=True):

    file_path = glob.glob(os.path.join(dir,"*.txt"))
Wiktor
  • 581
  • 1
  • 12
  • 23

1 Answers1

4

Filter your files with a list comprehension:

for dir, dirs, files in os.walk(src):
    files = [os.path.join(dir, f) for f in files if not f.endswith('.txt')]

I removed the topdown=True argument; it is the default.

Don't use glob.glob() in combination with os.walk(); both methods query the Operating System for the filenames in a directory. You already have those filenames at hand in the third value from each iteration over os.walk().

If you want to skip the whole directory, use the any() function to see if there are any matching files, then use continue ignore this directory:

for dir, dirs, files in os.walk(src):
    if any(f.endswith('.txt') for f in files):
        continue  # ignore this directory

    # do something with the files here, there are no .txt files.
    files = [os.path.join(dir, f) for f in files]

If you want to ignore this directory and all its descendants, clear out the dirs variable too using slice assignment:

for dir, dirs, files in os.walk(src):
    if any(f.endswith('.txt') for f in files):
        dirs[:] = []  # do not recurse into subdirectories
        continue      # ignore this directory

    # do something with the files here, there are no .txt files.
    files = [os.path.join(dir, f) for f in files]
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • And what if .txt files exist in subdirectories for example data----> folder -----> test.txt and i want to exclude subdirectory only ? – Wiktor Feb 09 '16 at 13:36
  • 1
    @WiktorKostrzewski: so you want to skip any directory that has a `.txt` file in it? – Martijn Pieters Feb 09 '16 at 13:37
  • Exactly :) this is my goal – Wiktor Feb 09 '16 at 13:37
  • i only want list of subdirectories which do not have .txt in them. My goal is to filter those subdirectories. Furthermore i want to move them to other position. I already did it for directories which contains .txt in them. – Wiktor Feb 09 '16 at 13:39
  • so to move directories without .txt on it i should use shutil in this loop ? – Wiktor Feb 10 '16 at 07:51
  • 1
    @WiktorKostrzewski: are there subdirectories too? Perhaps collect the directory paths in a list, then in a next step move all those matched directories. – Martijn Pieters Feb 10 '16 at 09:35
  • This is exactly what i was looking for.I am appreciate your help. Thanks man :) – Wiktor Feb 10 '16 at 14:41