gpt4 book ai didi

Python,如何根据列表重命名多个文件?

转载 作者:可可西里 更新时间:2023-11-01 11:13:36 25 4
gpt4 key购买 nike

在 Windows 中使用 python 我试图同时重命名同一文件夹中的多个文件,但我无法使用列表进行重命名,这就是我在尝试我的代码时出现此错误的原因:

os.rename(dirlist[1], words[1]) WindowsError: [Error 2] The system cannot find the file specified

示例代码如下:

import os
import sys
words = os.listdir('C:/Users/Any/Desktop/test')
dirlist = os.listdir('C:/Users/Any/Desktop/test')

words = [w.replace('E', 'e') for w in words]
print words

os.rename(dirlist[1], words[1])

我想要实现的是让我的 python 脚本在一个选择的文件夹上运行,脚本将获取那里的所有文件并重命名所有文件。但棘手的部分是当我无法挑出文件夹名称并重命名它们时,因为它们已附加到列表中。

最佳答案

os.listdir 仅返回基本名称结果。不是完整路径。它们不存在于您当前的工作目录中。您需要将它们与根一起加入:

root = 'C:/Users/Any/Desktop/test'
for item in os.listdir(root):
fullpath = os.path.join(root, item)
os.rename(fullpath, fullpath.replace('E', 'e'))

更新

为了回应您关于如何执行大量替换的评论,我建议您可以使用 translatemaketrans

让我们从字典和源字符串开始:

d = {'E': 'e', 'a': 'B', 'v': 'C'}
s = 'aAaAvVvVeEeE'

首先,让我向您展示一个非常原始和入门级方法的示例:

for old, new in d.iteritems():
s = s.replace(old, new)

print s
# BABACVCVeeee

该示例遍历您的字典,多次调用替换。它有效,而且非常有意义,使用简单的语法。但是不得不为每个字符串遍历字典并多次调用 replace 有点糟糕。

我相信还有很多其他方法可以做到这一点,但另一种方法是创建一次转换表,然后为每个字符串重复使用它:

import string

old, new = zip(*d.items())
print old, new
# ('a', 'E', 'v') ('B', 'e', 'C')

old_str, new_str = ''.join(old), ''.join(new)
print old_str, new_str
# aEv BeC

table = string.maketrans(old_str, new_str)

print s.translate(table)
# BABACVCVeeee

这会将字典拆分为键和值元组。然后我们连接 intro strings 并将它们传递给 maketrans,这将为我们返回一个表。我们只需要做一次。现在我们有了一个表,可以用它来翻译任何字符串。

关于Python,如何根据列表重命名多个文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11916625/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com