pythonchdir

Python change directory to folder starting by


Is there a way to change directory in Python to a folder starting by a fixed character, but the rest of the name use a "whatever the rest of the name"?

path = os.getenv("HOME")  
os.chdir(path +'/test/Reports/' + year + '/' + mounth + '/')

The variable mounth is the numeric current mounth, but the actual mounth folders are the number of the mounth plus the name. So I would like to change directory to a folder that starts with the number of the mount but with something else (as pressing in bash the tab to autofill the rest of the name when it gets a match).


Solution

  • You can use glob for wildcard matching, and pass that to os.chdir.

    import os
    from glob import glob
    
    dirname = glob('/test/Reports/' + year + '/' + mounth + '*')
    os.chdir(dirname[0])