Rename multiple files in Python

后端 未结 6 1120
梦如初夏
梦如初夏 2020-12-01 08:14

How can I rename the following files:

abc_2000.jpg
abc_2001.jpg
abc_2004.jpg
abc_2007.jpg

into the following ones:

year_200         


        
6条回答
  •  南方客
    南方客 (楼主)
    2020-12-01 09:15

    This allows to rename the file with the creation date_time.

    import os, datetime, time
    
    folder = r"*:\***\***\TEST"
    
    for file in os.listdir(folder):
        date = os.path.getmtime(os.path.join(folder, file))
        new_filename = datetime.datetime.fromtimestamp(date).strftime("%Y%m%d_%H%M%S.%f")[:-4]
        os.rename(os.path.join(folder, file), os.path.join(folder, new_filename + ".pdf"))
        print("Renamed " + file + " to " + new_filename)
        time.sleep(0.1)
    

提交回复
热议问题