Robin46
Robin46

Reputation: 34

Using Python to search specific file names in (sub)folders

I'am trying to make a file searching, Python based program, with GUI. It's going to be used to search specified directories and subdirectories. For files which filenames have to be inserted in an Entry-box. while I'am fairly new to python programming, I searched the web and gained some information on the os module.

Then I moved on and tried to write a simple code with os.walk and without the GUI program:

import os
for root, dirs, files in os.walk( 'Path\to\files'):
    for file in files:
       if file.endswith('.doc'):
        print(os.path.join(root, file))

Which worked fine, however... file.endswith() Only looks to the last part of the filename. The problem is that in the file path are over 1000 files with .doc. And I want the code to be able to search parts of the file name, for example "Caliper" in filename "Hilka_Vernier_Caliper.doc".

So I went on and searched for other methods than file.endswith() and found something about file.index(). So I changed the code to:

import os
    for root, dirs, files in os.walk( 'Path\to\files'):
        for file in files:
           if file.index('Caliper'):
            print(os.path.join(root, file))

But that didn't work as planned... Does someone on here have an idea, how I could make this work?

Upvotes: 0

Views: 504

Answers (1)

vpoulailleau
vpoulailleau

Reputation: 108

You may use pathlib instead of the old os: https://docs.python.org/3/library/pathlib.html#pathlib.Path.rglob

BTW, file.index raises an exception if the name is not not found, so you need a try/except clause.

Another way is to use if "Caliper" in str(file):

Upvotes: 2

Related Questions