实验描述
现有一堆数据命名错误,有些文件中有括号和数字的后缀,要将(i)
改为_i
.如下表所示
原名称 | 修改后名称 |
---|---|
data(1).twf | data _1.twf |
data(1).tif | data _1.tif |
data(1).aux.xml | data _1.aux.xml |
实现思路
- 先读取整个文件,将整个文件夹中含有
(i)
的文件找到,写入CSV,列名为old_name
。 - 创建新的一列,列名为
new_name
。将old_name
中的'('
替换为'_'
,')'
删去, - 将上述操作后的结果存入
new_name
即可;
参考代码如下:
with open(dir+"\\"+"file.csv","w",newline = '\n') as f:
csv_writer = csv.writer(f)
#写表头
csv_writer.writerow(['old_name','new_name'])
for row in nameList:
row_ = row.replace('(','_')
row_ = row_.replace(')','')
csv_writer.writerow([row,row_])
f.close
- 通过os包中的
rename('old_name','new_name')
函数,根据csv文件即可实现改名。
os.rename('old_name','new_name')
完整代码
import os
import csv
import pandas as pd
suffix = ['.twf','.tif','.aux.xml','.txt']
dir = r'F:data'
nameList = []
for file in os.listdir(dir):
if '(' in file and ')' in file:
nameList.append(file)
for i in range(len(nameList)):
nameList[i] = nameList[i]
with open(dir+"\\"+"file.csv","w",newline = '\n') as f:
csv_writer = csv.writer(f)
#写表头
csv_writer.writerow(['old_name','new_name'])
for row in nameList:
row_ = row.replace('(','_')
row_ = row_.replace(')','')
csv_writer.writerow([row,row_])
f.close
print("finished")
print(nameList)
path = dir + r'\file.csv'
data = pd.read_csv(path,encoding='UTF-8',usecols = ['old_name','new_name'])
modList = data.values.tolist()#[[oldName,newName],....]
for name in modList:
os.rename(dir+'/'+name[0],dir+r'/'+name[1])
print(name[0]+' → '+name[1]+" 已完成")# 打印结果:xxx (4).tif → xxx _4.tif 已完成