Batch Renaming of Files in a Directory

前端 未结 13 1502
孤街浪徒
孤街浪徒 2020-11-27 09:41

Is there an easy way to rename a group of files already contained in a directory, using Python?

Example: I have a directory full of *.doc files an

13条回答
  •  不知归路
    2020-11-27 10:01

    If you don't mind using regular expressions, then this function would give you much power in renaming files:

    import re, glob, os
    
    def renamer(files, pattern, replacement):
        for pathname in glob.glob(files):
            basename= os.path.basename(pathname)
            new_filename= re.sub(pattern, replacement, basename)
            if new_filename != basename:
                os.rename(
                  pathname,
                  os.path.join(os.path.dirname(pathname), new_filename))
    

    So in your example, you could do (assuming it's the current directory where the files are):

    renamer("*.doc", r"^(.*)\.doc$", r"new(\1).doc")
    

    but you could also roll back to the initial filenames:

    renamer("*.doc", r"^new\((.*)\)\.doc", r"\1.doc")
    

    and more.

提交回复
热议问题