【问题标题】:Python Script to Remove Characters and Replace in Filenames用于删除字符并替换文件名的 Python 脚本
【发布时间】:2017-10-19 17:15:01
【问题描述】:

我有一个 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)

您可以为这个新手提供任何帮助,我们将不胜感激。

【问题讨论】:

    标签: python filenames


    【解决方案1】:

    使用字典来跟踪您的替换。然后,您可以循环其键和值,如下所示:

    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)
    

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

    【讨论】:

      【解决方案2】:

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

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

      语法如下:

      def func_name(paramater1,paramater2...):

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

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

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

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

      【讨论】:

      • 哦,我刚刚看到了我之前的答案,我喜欢它只编辑文件名的方式,效率更高。我建议你使用他们的答案,但我会留下我的答案,以防你发现这个替代想法有用。
      猜你喜欢
      • 1970-01-01
      • 2021-07-03
      • 1970-01-01
      • 2020-11-18
      • 1970-01-01
      • 1970-01-01
      • 2015-04-12
      • 2021-01-10
      • 1970-01-01
      相关资源
      最近更新 更多