首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >使用python复制文件并基于CSV对其进行重命名

使用python复制文件并基于CSV对其进行重命名
EN

Stack Overflow用户
提问于 2018-08-10 04:04:57
回答 1查看 961关注 0票数 0

我有大约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] + '!'
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-08-10 04:37:46

如果你是Python的新手,我建议你使用Pandas来解决这个问题。

下面是我将如何设置它。

假设您有包含old_namenew_name列的csv文件。

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中,我们有以下文件:

import os 
os.listdir('start_location')
['old_1.txt', 'old_4.txt', 'old_2.txt', 'old_3.txt']

我们的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
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51774990

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档