【问题标题】:How to use wildcard in renaming multiple files in a directory in Python如何使用通配符重命名Python目录中的多个文件
【发布时间】:2021-05-26 11:12:24
【问题描述】:

我是编码新手。 是否可以使用通配符来重命名目录中的文件?

例如一个文件夹中有两个文件:

asdxyd01.pdf

cdc1pxych001.pdf

想要通过删除“xy”之前的所有字符来重命名文件。

我正在使用以下代码,它非常适合仅删除特定单词。

# Function to replace words in files names in a folder
import os
def main():
    i = 0

    # Ask user where the PDFs are
    path = input('Folder path to PDFs: ')
    # Sets the scripts working directory to the location of the PDFs
    os.chdir(path)
    
    filetype = input('entre file extention here: ')
    rep = input('entre word to remove from file name: ')

    for filename in os.listdir(path):
                        
        my_dest = filename.replace(rep, "") +"."+filetype
                
        my_source = filename
        my_dest = my_dest
        # rename() function will
        # rename all the files
        os.rename(my_source, my_dest)
        i += 1


# Driver Code
if __name__ == '__main__':
    # Calling main() function
    main()

【问题讨论】:

    标签: python python-3.x wildcard


    【解决方案1】:

    根据您的问题,我假设您希望将文件重命名为:xyd01.pdf、ch001.pdf。 首先,让我们看看你的错误:

    my_dest = filename.replace(rep, "") +"."+filetype
    

    在这里,通过将 'rep' 替换为 '',您基本上是从名称中删除了模式,而不是之前的字符。 因此,要实现您的目标,您需要找到匹配模式的出现并替换它之前的子字符串。你可以这样做:

    index=filename.find(rep)
    prefix=filename[:index]
    my_dest = filename.replace(prefix, "")
    

    看,我也没有在目的地末尾添加"."+filetype,因为它会使替换文件看起来像这样:xyd01.pdf.pdf

    现在您应该在运行此代码时考虑更多的事情。如果你没有在 for 循环的最开始做任何检查,你的程序将重命名任何具有相同模式的文件名,所以在下面添加这个条件:

     if filetype not in filename:
             continue
    

    最后,另一个检查对于在切片文件名时防止无效的数组索引很重要:

        index=filename.find(rep)
        if index<=0:
            continue
    

    整体看起来是这样的:

    for filename in os.listdir(path):
        if filetype not in filename:
            continue
        index=filename.find(rep)
        if index<=0:
            continue
        prefix=filename[:index]
        my_dest = filename.replace(prefix, "")                                            
        my_source = filename
        os.rename(my_source, my_dest)
        i += 1 # this increment isn't necessary
    

    【讨论】:

      猜你喜欢
      • 2016-09-24
      • 2018-12-25
      • 2021-03-28
      • 2015-04-23
      • 2016-07-09
      • 2011-02-15
      • 2018-11-01
      • 1970-01-01
      • 2014-10-19
      相关资源
      最近更新 更多