简体   繁体   中英

How to rename the list of files in a folder

I have set of 100 files in a folder. I need to rename the files. My input files are like

 1) 0000000001.001
 2) 0000000001.002
 3) 0000000001.003
 4) 0000000002.001
 5) 0000000002.002
 6) 0000000002.003
 7) 0000000003.001
 8) 0000000003.002
 9) 0000000003.003

I have tried this:

import os

folder ="C:/Users/xyz"

rename_dict = {'001': '1', '002': '2', '005': '5'}
for filename in os.listdir(folder):
    base_file, ext = os.path.splitext(filename)
    ext = ext.replace('.','')
    if ext in rename_dict:
        new_ext = rename_dict[ext]
        new_file = base_file + new_ext
        old_path = os.path.join(folder, filename)
        new_path = os.path.join(folder, new_file)
        os.rename(old_path, new_path)

Excepted output:

 1) 0000000101.1
 2) 0000000101.2
 3) 0000000101.3
 4) 0000000102.1
 5) 0000000102.2
 6) 0000000102.3
 7) 0000000103.1
 8) 0000000103.2
 9) 0000000103.3

I need to rename the file names in an incremental way.

Here you go (assuming they are .txt files)

import os
folder ="C:\\Users\\xyz\\"
os.chdir(folder)
for filename in os.listdir(folder):
    newName = filename.split(".")[0] + "." +  filename.split(".")[1][-1:] + '.txt'   
    print newName
    os.rename(filename, newName)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM