首页 > 解决方案 > 如果文件名是字符串列表的子字符串,则使用父字符串重命名文件

问题描述

我在目录中有文件,文件名是字符串列表的子字符串。我需要用列表中的字符串重命名文件

filenames in "./temp" = aa.txt, bb.txt, cc.txt    
list_of_names = ['aa12.txt', 'bb12.txt', 'cc12.txt']

我希望将文件重命名为list_of_names. 尝试了下面的代码,但得到一个错误

for filename in os.listdir('./temp'):
for i, item in enumerate(list_of_names):
    if filename in item:
        os.rename(filename,list_of_names[I])

FileNotFoundError:[Errno 2] 没有这样的文件或目录:'aa.txt' -> 'aa12.txt'

标签: pythonstringlistfile-iopython-os

解决方案


尝试:

os.rename(‘./temp/‘ + filename, ‘./temp/‘+ list_of_names[i])

此外,考虑使用 pathlib 进行文件系统操作。


推荐阅读