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

时间:2013-11-17 16:55:52

标签: python csv file-rename

您好我一直在努力调整this以满足我的需求,但我只是python中的newbe,我有一个包含多个列和行的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)

非常感谢。

3 个答案:

答案 0 :(得分:2)

您应该使用从CSV创建的词典IDs

for filename in os.listdir(path):
    oldname = filename
    newname = IDs[oldname]
    os.rename(path + filename, tmpPath + newname)

但你可能应该使用某种错误检查..(编辑正如其他答案指出最好也使用os.path.join)也许这些内容:

failed = []
for oldname in os.listdir(path):
    try:
        old = os.path.join(path, oldname)
        new = os.path.join(tmpPath, IDs[oldname])
        os.rename(old, new)
    except KeyError, OSError:
        failed.append(oldname)

print failed

答案 1 :(得分:2)

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

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] + '!'

答案 2 :(得分:1)

您正在迭代该文件并在IDs中存储旧名称和新名称,但不要使用它,只是尝试从文件中进一步阅读(由于您已经阅读了整个文件,因此显然会失败)到那个时候的文件)。您应该使用IDs dict来获取新名称(使用oldname作为键),即:

path = 'txt_orig' # no trailing slash required
tmpPath = 'txt_tmp' # idem
for filename in os.listdir(path):
    try:
       newname = IDs[filename]
    except KeyError:
       print "no new name for '%s'" % filename
       continue
    else:     
        os.rename(os.path.join(path, filename), os.path.join(tmpPath, newname))

现在有一个更简单的解决方案:只需在迭代csv文件时重命名文件:

path = 'txt_orig'
tmp_path = 'txt_tmp'

with open('documentos_corpus_ladino.csv','rb') as csvfile:
    reader = csv.reader(csvfile, delimiter = ',')
    for row in reader:
       oldname = os.path.join(path, row[0])
       if os.path.exists(oldname):
           newname = os.path.join(tmp_path, row[1])
           os.rename(oldname, newname)
           print >> sys.stderr, "renamed '%s' to '%s'" % (oldname, newname)
       else:
           print >> sys.stderr, "file '%s' not found" % oldname
相关问题