How to use glob in python to search through a specific folder
<p>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. </p>

<p>At the moment, the user enters the filename using this code:</p>

<pre><code>src = input("Please enter the folder path where the files are located")
</code></pre>

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

<pre><code>for f in glob.glob("*reference*" + "*letter*"):
    new_filename = "203 Reference Letter" + " " + name  
    os.rename(f,new_filename)
</code></pre>

<p>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? </p>

<p>Any help is greatly appreciated! Thank!</p>

<p>You can use <a href="https://docs.python.org/3/library/os.path.html#os.path.join" rel="nofollow">os.path.join</a> to join the user input to the desired pattern:</p>

<pre><code>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.')
    exit(1)

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)
</code></pre>

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

python python-3.x glob