【问题标题】:Python rename files reading names from csv filePython重命名文件从csv文件中读取名称
【发布时间】: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


【解决方案1】:

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

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

【讨论】:

  • 非常感谢,效果很好。无论如何我怎么能复制文件而不是移动它们,我的意思是保留原始文件?
  • @AndrésChandía 当然,只需使用shutil.copy(source, dest) 而不是os.rename(source, dest) 来复制文件而不是移动。
  • 不工作,对于它说“无法重命名为”的所有文件,这就是我所说的:shutil.copy(os.path.join(path, oldname), os. path.join(destPath, IDs[oldname]))
  • 这听起来像是一个权限问题,无论是文件被替换还是文件被复制。如果是与正在复制的文件一起使用,则使用不复制权限的shutil.copyfile 可能会起作用。
  • 抱歉,还是不行,代码:IDs = {} with open('documentos_corpus_ladino.csv','rb') as csvfile: timeReader = csv.reader(csvfile, delimiter = ',' ) for row in timeReader: IDs[row[0]] = row[1] path = 'txt_orig/' destPath = 'txt/' for oldname in os.listdir(path): if oldname in IDs: try: shutil.copyfile (os.path.join(path, oldname), os.path.join(destPath, IDs[oldname])) 除外: print 'File ' + oldname + ' 不能重命名为 ' + IDs[oldname] + '! '
【解决方案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

【讨论】:

  • 非常感谢,尽管这两个代码都有一些问题。如果输入目录中有一个不在 csv 文件中的文件,则脚本将停止,即使文件名包含任何字符,如 ñ 或 ç
  • @AndrésChandía:你说得对,我现在看到如果你使用 Python 2,我的代码会因 Unicode 字符而失败。但我认为 try 块应该解决这个问题,脚本应该在至少完成.. 嗯很奇怪。
【解决方案3】:

您正在对文件进行迭代并将旧名称和新名称存储在 IDs 中,但不要使用它,而只是尝试从文件中进一步读取(这显然会失败,因为您已经通过那时)。 IOW 你应该使用你的IDs dict 来获取新名称(使用旧名称作为键),即:

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

【讨论】:

  • 非常感谢,当文件名包含 ñ 或 ç 等字符时,您的第一个代码会出错,但第二个代码效果很好。无论如何,我怎么能复制文件而不是移动它们,我的意思是保留原始文件?
【解决方案4】:

这是我在使用上述 sn-ps 没有成功后想出的。您可以在没有 pandas 的情况下执行此操作,但我还需要进行格式化并从我的数据中删除一些重复值,以便 pandas 让我的生活更轻松。

import os
import pandas as pd


csv_name = "/home/your_filename.csv"
#parent_dir is the directory that has the folders you want to rename
parent_dir = "/path/to/folder"
df  =  pd.read_csv(csv_name)

list_oldnames = df['Old_Name'].astype(str).to_list()

list_newnames = df['New_Name'].astype(str).to_list()

for folder in os.listdir(parent_dir):
    for oldname, newname in zip(list_oldnames, list_newnames):
        if str(oldname) == str(folder):
            try:
                os.rename(os.path.join(parent_dir, oldname), os.path.join(parent_dir, newname))
            except:
                print("Could not rename "+ str(os.path.join(parent_dir, oldname)) )

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-06-01
    • 2020-04-11
    • 2021-05-24
    • 2011-07-04
    • 2021-01-06
    • 2017-05-17
    • 2017-12-23
    • 1970-01-01
    相关资源
    最近更新 更多