Batch Renaming of Files in a Directory

前端 未结 13 1459
孤街浪徒
孤街浪徒 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:12

    Such renaming is quite easy, for example with os and glob modules:

    import glob, os
    
    def rename(dir, pattern, titlePattern):
        for pathAndFilename in glob.iglob(os.path.join(dir, pattern)):
            title, ext = os.path.splitext(os.path.basename(pathAndFilename))
            os.rename(pathAndFilename, 
                      os.path.join(dir, titlePattern % title + ext))
    

    You could then use it in your example like this:

    rename(r'c:\temp\xx', r'*.doc', r'new(%s)')
    

    The above example will convert all *.doc files in c:\temp\xx dir to new(%s).doc, where %s is the previous base name of the file (without extension).

提交回复
热议问题