嗨,我一直在努力使this适应我的需要,但我只是一个python新手,我有一个csv文件有多个列和行,重要的列是1=旧文件名,2=新文件名,所以我需要转到csv文件中列出的文件所在的目录,并将它们重命名为列2的新名称,正如我所说,我已经尝试了很多没有成功的事情,我粘贴了最后一个代码,所以你有一个想法:
import os, unicodecsv as csv, sys
IDs = {}
#open and store the csv file
with open('documentos_corpus_ladino.csv','rb') as csvfile:
timeReader = csv.reader(csvfile, delimiter = ',')
# build a dictionary with the associated IDs
for row in timeReader:
IDs[ row[0] ] = row[1]
# #get the list of files
path = 'txt_orig/'
tmpPath = 'txt_tmp/'
for filename in os.listdir('txt_orig/'):
oldname = filename
newname = filename.replace(oldname, csvfile.next().rstrip().split(",")[1])
os.rename(path + filename, tmpPath + newname)
非常感谢。
您应该使用从CSV创建的字典
IDs
:但是你可能应该使用某种错误检查。。(编辑正如其他答案所指出的,最好也使用
os.path.join
)可能是以下内容:这将重命名每个匹配的文件,并报告试图重命名的任何错误。它不会试图移动不存在的文件。
您正在对文件进行迭代,并将新旧名称存储在
IDs
中,但不要使用它,只需尝试从文件中进一步读取(这显然会失败,因为此时您已经读取了整个文件)。你应该用你的IDs
指令来获取新的名字(用旧名字作为键),例如:现在有一个更简单的解决方案:只要在csv文件上迭代时重命名文件:
相关问题 更多 >
编程相关推荐