Python 用于删除字符并替换文件名的脚本

Python Script to Remove Characters and Replace in Filenames

我有一个 python 脚本,它查看文件夹中的所有文件以查找特定单词并将该单词替换为 space。我不想在每次 运行 脚本后更改要查看的单词,而是想继续为脚本添加新单词以查找并执行相同的替换操作。

我在 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)

如果您能为这位新手提供任何帮助,我们将不胜感激。

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

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)

这会一次性应用所有替换文件,并且只重命名文件一次。

每当您看到自己一次又一次地使用代码块并只进行一次更改时,通常最好将它们转换为函数。

在 Python 中定义函数既快速又容易。它们需要在您使用它们之前定义,因此它们通常位于导入语句之后的文件顶部。

语法如下所示:

def func_name(paramater1,paramater2...):

然后函数的所有代码都在def子句下缩进。

我建议您将 for path in paths 语句及其下的所有内容作为函数的一部分,并将要搜索的词作为参数传入。

然后,定义函数后,您可以列出文件名中要替换的所有单词,运行函数如下:

word_list = [.File, Generic]
for word in word_list:
    my_function(word)