0

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?

1 Answer 1

2

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):

Sign up to request clarification or add additional context in comments.

1 Comment

thank you for your comment vpoulailleau, I'll dive in the pathlib :-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.