Bug in Python Renaming Program…No such file or Directory (Fnmatch)

后端 未结 2 1281
刺人心
刺人心 2020-12-18 11:06

I\'m trying to build a little renaming program to help save me time in the future. Basically it will go through directories I point it too and rename files if they meet cert

相关标签:
2条回答
  • 2020-12-18 11:31

    You'll need to include the full path to the filenames you are trying to rename:

    import os
    import fnmatch
    
    directory = "/Users/Desktop/TESTME"
    for file in os.listdir(directory):
        if fnmatch.fnmatch(file, 'MISC*'):
            path = os.path.join(directory, file)
            target = os.path.join(directory, file[4:12] + '-13-Misc.jpg'
            os.rename(path, target)
    

    The os.path.join function intelligently joins path elements into a whole, using the correct directory separator for your platform.

    0 讨论(0)
  • 2020-12-18 11:44

    The function os.listdir() only returns the file names of the files in the given directory, not their full paths. You can use os.path.join(directory, file_name) to reconstruct the full path of the file.

    You could also do this in bash:

    cd /Users/Desktop/TESTME/
    for f in MISC*; do mv "$f" "${f:4:8}-13-Misc.jpg"; done
    
    0 讨论(0)
提交回复
热议问题