Batch Renaming of Files in a Directory

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

    I had a similar problem, but I wanted to append text to the beginning of the file name of all files in a directory and used a similar method. See example below:

    folder = r"R:\mystuff\GIS_Projects\Website\2017\PDF"
    
    import os
    
    
    for root, dirs, filenames in os.walk(folder):
    
    
    for filename in filenames:  
        fullpath = os.path.join(root, filename)  
        filename_split = os.path.splitext(filename) # filename will be filename_split[0] and extension will be filename_split[1])
        print fullpath
        print filename_split[0]
        print filename_split[1]
        os.rename(os.path.join(root, filename), os.path.join(root, "NewText_2017_" + filename_split[0] + filename_split[1]))
    

提交回复
热议问题