你好,我一直在努力适应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)
多谢。
这将重命名每个匹配的文件,并报告尝试重命名的任何错误。它不会尝试移动不存在的文件。
import os, unicodecsv as csv
# open and store the csv file
IDs = {}
with open('documentos_corpus_ladino.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 = 'txt_orig/'
tmpPath = 'txt_tmp/'
for oldname in os.listdir(path):
# ignore files in path which aren't in the csv file
if oldname in IDs:
try:
os.rename(os.path.join(path, oldname), os.path.join(tmpPath, IDs[oldname]))
except:
print 'File ' + oldname + ' could not be renamed to ' + IDs[oldname] + '!'
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)