如何使用通配符重命名 Python 目录中的多个文件

How to use wildcard in renaming multiple files in a directory in Python

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

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

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()

根据您的问题判断,我假设您希望将文件重命名为: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