Python遍历文件,修改文件名

Python遍历文件,修改文件名
Python 遍历文件夹下的‘.raw’文件,并按照‘csv’文件中的重命名规则进行修改

// An highlighted block
import os
import csv

#the relationship between old & new file names  is  in 'AF.csv'
with open('AF.csv','r') as csvfile:  
    reader = csv.reader(csvfile)   
    wfdbnames = []  #new names
    rawnames = []   #old names
    for row in reader:
        if row[0] != 'wfdbnames':
            wfdbnames.append(row[0])
        if row[11] != 'rawnames':
            rawnames.append(row[11])
            
path = 'AF'
rawlist = os.listdir(path)
print(rawlist,len(rawlist))

for i in rawlist:   #
    for j in rawnames:
        idx = rawnames.index(j)
        try:
            if j == i:
                old = path + '\\'+ i
                new = path + '\\'+ wfdbnames[idx] + '.raw'
                os.renames(old,new)
        except FileNotFoundError:
            print("系统找不到指定的文件。:"+ old +  "->" + new)

你可能感兴趣的:(python)