Python,如何在折叠中找到以特定格式结尾的文件

2024-03-29 07:15:28 发布

您现在位置: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结尾的文件夹中查找特定文件,以便移动它们。 我在搜索多个文件夹时遇到问题。你知道吗


Tags: pathinimport文件夹forosmyfiles
3条回答

首先你走错了路 应该是的

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

然后要获取扩展名为.kfm的文件,还可以使用以下代码

import os
files = os.listdir(path)
kfm_files=[f for f in files if '.kfm' in f]

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

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

行不通

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

*不需要。你知道吗

也像在注释中一样,您应该使用endswith来避免文件名中包含“.kfm”而不是文件扩展名。你知道吗

下面将为您提供当前目录树下的文件列表,并带有指定的后缀。你知道吗

from pathlib import Path

filelist = list( Path( '.' ).glob('**/*.kfm') )

print( filelist )

在下面,我们更进一步。我们对文件列表进行排序,然后对文件进行循环

from pathlib import Path

mysubdir = 'whatever'

pathlist = Path( mysubdir).glob('**/*.kfm')

filelist = sorted( [str(file) for file in pathlist] )

for file in filelist:
    print( file )

相关问题 更多 >