Python重命名文件从csv文件读取名称

And*_*día 6 python csv file-rename

您好,我一直在尝试使其适应的需求,但我只是 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)
Run Code Online (Sandbox Code Playgroud)

多谢。

Pi *_*ion 5

这将重命名每个匹配的文件,并报告尝试重命名的任何错误。它不会尝试移动不存在的文件。

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] + '!'
Run Code Online (Sandbox Code Playgroud)