首页 > 解决方案 > Python,我如何在文件夹中找到以特定格式结尾的文件

问题描述

import shutil, os

path = 'C:\\Users\\cHaTrAp\Documents\\My Games\\KillingFloor2\\KFGame\\Cache\\*'

files = []
# r=root, d=directories, f = files
for r, d, f in os.walk(path):
    for file in f:
        if '.kfm' in file:
            files.append(os.path.join(r, file))

for f in files:
    print(f)

我正在尝试在以 .kfm 结尾的文件夹中查找特定文件,以便我可以移动它们。我在搜索多个文件夹时遇到问题。

标签: python

解决方案


你做的一切都很好,但你的道路是错误的。

path = 'C:\\Users\\cHaTrAp\Documents\\My Games\\KillingFloor2\\KFGame\\Cache\\*'

行不通

path = 'C:\\Users\\cHaTrAp\Documents\\My Games\\KillingFloor2\\KFGame\\Cache'

* 不是必需的。

就像在评论中一样,您应该使用 endwith 来避免名称中包含“.kfm”的文件,而不是作为文件扩展名。


推荐阅读