如果您是Python的新手,我建议您使用Pandas来解决这个问题。在
下面是我如何设置它。在
假设您的csv文件包含old_name和new_name列。在import pandas as pd
name_map = pd.read_csv('old-names-new-names.csv')
name_map.head()
new_name old_name
0 new_33.txt old_1.txt
1 new_18.txt old_2.txt
2 new_29.txt old_3.txt
3 new_31.txt old_4.txt
4 new_64.txt old_1.txt
在start_location中,我们有以下文件:
^{pr2}$
我们的save_location目录为空。在
要复制这些文件,我们可以像这样在Pandas数据框上快速循环,使用shutil将文件复制到新目录中,new_name列中的名称。在import shutil
for i, r in name_map.iterrows():
shutil.copy('start_location/{}'.format(r.old_name), 'save_location/{}'.format(r.new_name))
当我们检查我们的目的地目录时,我们看到所有的东西都在那里:os.listdir('save_location')
['new_60.txt',
'new_29.txt',
'new_31.txt',
'new_64.txt',
'new_48.txt',
'new_33.txt',
'new_96.txt',
'new_18.txt']
如果不想使用pandas,请考虑以下选项:import os
import csv
import shutil
with open('old-names-new-names.csv','rt') as csvfile:
timeReader = csv.reader(csvfile, delimiter = ',')
i = 0
for row in timeReader:
if i > 0:
start_loc = row[1]
save_loc = row[0]
shutil.copy('start_location/{}'.format(start_loc), 'save_location/{}'.format(save_loc))
i+=1