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

2024-10-05 14:30:50 发布

您现在位置:Python中文网/ 问答频道 /正文

嗨,我一直在努力使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)

非常感谢。


Tags: 文件csvthecsvfiletxtidsforos
3条回答

您应该使用从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

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

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

您正在对文件进行迭代,并将新旧名称存储在IDs中,但不要使用它,只需尝试从文件中进一步读取(这显然会失败,因为此时您已经读取了整个文件)。你应该用你的IDs指令来获取新的名字(用旧名字作为键),例如:

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

相关问题 更多 >