【发布时间】:2021-08-13 23:43:20
【问题描述】:
嗨,我一直在尝试使 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)
非常感谢。
【问题讨论】:
-
我相信 ID 字典,您已经将旧文件名映射到新文件名。因此,您应该只遍历该字典并重命名文件。为什么需要先使用 os.listdir() 列出文件?
-
如果您从以下任何一项中得到答案,请投票并接受。或者评论说你到底需要什么。
标签: python csv file-rename