Python脚本:删除文件名中的字符并替换

3
我有一个Python脚本,它会查找文件夹中所有文件中特定的单词,并将该单词替换为空格。我希望在不更改要查找的单词的情况下,继续添加新的单词供脚本查找并执行相同的替换操作。
我在macOS El Capitan上运行此脚本。下面是该脚本:
import os

paths = (os.path.join(root, filename)
        for root, _, filenames in os.walk('/Users/Test/Desktop/Test')
        for filename in filenames)

for path in paths:
    # the '#' in the example below will be replaced by the '-' in the filenames in the directory
    newname = path.replace('.File',' ')
    if newname != path:
        os.rename(path, newname)

for path in paths:
    # the '#' in the example below will be replaced by the '-' in the filenames in the directory
    newname = path.replace('Generic',' ')
    if newname != path:
        os.rename(path, newname)

能够提供给这个新手的任何帮助都将不胜感激。

2个回答

8
使用字典来跟踪您的替换。你可以遍历它的键和值,像这样:
import os

paths = (os.path.join(root, filename)
        for root, _, filenames in os.walk('/Users/Test/Desktop/Test')
        for filename in filenames)

# The keys of the dictionary are the values to replace, each corresponding
# item is the string to replace it with
replacements = {'.File': ' ',
                'Generic': ' '}

for path in paths:
    # Copy the path name to apply changes (if any) to
    newname = path 
    # Loop over the dictionary elements, applying the replacements
    for k, v in replacements.items():
        newname = newname.replace(k, v)
    if newname != path:
        os.rename(path, newname)

这将一次性应用所有替换,并仅重命名文件一次。

1
每当你发现自己在重复使用一段代码,只是改变了一个小部分时,通常最好将它们转换为函数。
在Python中定义函数非常快捷简单。它们需要在使用前定义,通常放在导入语句后的文件顶部。
语法如下:
def func_name(parameter1,parameter2...):
然后所有函数代码都缩进在"def"子句下面。
我建议您将 "for path in paths" 语句及其下面的所有内容作为函数的一部分,并将要搜索的单词作为参数传递。
然后,在定义函数之后,您可以制作所有要替换文件名中的单词列表,并在运行函数时这么做:
word_list = [.File, Generic]
for word in word_list:
    my_function(word)

哦,我刚看到比我的答案更好的答案了,我喜欢它只编辑文件名一次,这样更高效。我建议你使用他们的答案,但如果你觉得这个替代方案有用的话,我也会留下我的答案。 - Davy M

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接