【发布时间】:2019-01-17 09:20:57
【问题描述】:
我有大约 400 个文件需要根据 csv 文件复制和重命名,其中一些文件将被复制多次并给出不同的名称。
我有 CSV 文件,在 A 列中它具有原始名称,在 B 列中具有新名称。
IE 1000.jpg 1000 - 10x10.jpg 1000.jpg 1000 - 12x12.jpg
我编写的 python 脚本将复制文件、重命名并移动,但只移动一次。所以如果我需要 4 份 1000.jpg 重命名,我只会得到一份。
我对此仍然非常陌生,因此非常感谢任何帮助。
import os
import csv
import shutil
# open and store the csv file
IDs = {}
with open('old-names-new-names.csv','rb') as csvfile:
timeReader = csv.reader(csvfile, delimiter = ',')
# build dictionary with associated IDs
for row in timeReader:
IDs[row[0]] = row[1]
# move files
path = '/start_location/'
tmpPath = '/save_location/'
for oldname in os.listdir(path):
# ignore files in path which aren't in the csv file
if oldname in IDs:
try:
shutil.copy(os.path.join(path, oldname), os.path.join(tmpPath, IDs[oldname]))
except:
print 'File ' + oldname + ' could not be renamed to ' + IDs[oldname] + '!'
【问题讨论】: