Ruthus99 Ruthus99 - 1 year ago 109
Python Question

How to use glob in python to search through a specific folder

I am currently working on a small piece of code that I want to go through a user-inputted folder and rename all the files in there depending on certain criteria.

At the moment, the user enters the filename using this code:

src = input("Please enter the folder path where the files are located")

Then, I use the glob module to rename the files if they meet certain criteria, e.g:

for f in glob.glob("*reference*" + "*letter*"):
new_filename = "203 Reference Letter" + " " + name

Now all this works perfectly if the .py script is located in the folder with all the files in it, however my question is as follows: How can I basically combine the 2 bits of code above? Basically, how do I make it so that the user inputs a filepath, and the glob module then takes that path and renames the files in that folder?

Any help is greatly appreciated! Thank!

Answer Source

You can use os.path.join to join the user input to the desired pattern:

import os.path

src = input('Please enter the folder path where the files are located: ')
if not os.path.isdir(src):
    print('Invalid given path.')

path = os.path.join(src, '*reference*letter*')
for f in glob.glob(path):
    new_filename = '203 Reference Letter {}'.format(name)
    os.rename(f, new_filename)

I do not know what is the pattern used in glob, but basically you join the user input folder to any pattern.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download