Rename multiple files in Python

后端 未结 6 1127
梦如初夏
梦如初夏 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:06

    # By changing one line in code i think this line will work or may be without changing anything this will work

    import glob2
    import os
    
    
    def rename(f_path, new_name):
        filelist = glob2.glob(f_path + "*.ma")
        count = 0
        for file in filelist:
            print("File Count : ", count)
            filename = os.path.split(file)
            print(filename)
            new_filename = f_path + new_name + str(count + 1) + ".ma"
            os.rename(f_path+filename[1], new_filename)
            print(new_filename)
            count = count + 1
    

    Call the function by passing two arguments f_path as your path and new_name as you like to give to file.

提交回复
热议问题