[英]Python, how do i find files that end with a specific format in a folder
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)
I am trying to find a specific files in a folder that ends with .kfm so i can move them.我试图在以 .kfm 结尾的文件夹中查找特定文件,以便我可以移动它们。 I am having problem to search multiple folder.
我在搜索多个文件夹时遇到问题。
you are doing everything fine but your path is wrong.你做的一切都很好,但你的道路是错误的。
path = 'C:\\Users\\cHaTrAp\Documents\\My Games\\KillingFloor2\\KFGame\\Cache\\*'
won't work不会工作
path = 'C:\\Users\\cHaTrAp\Documents\\My Games\\KillingFloor2\\KFGame\\Cache'
the * is not needed. * 不是必需的。
Also like in the comment you should use endswith to avoid files that has '.kfm' in their name instead as file extension.也像在评论中一样,您应该使用 Endswith 来避免名称中包含“.kfm”的文件而不是文件扩展名。
The following will give a you a list of files under the current directory tree, with the specified suffix.下面会给你一个当前目录树下的文件列表,带有指定的后缀。
from pathlib import Path
filelist = list( Path( '.' ).glob('**/*.kfm') )
print( filelist )
In the following, we go a step further.下面,我们更进一步。 We sort the filelist, and then loop over the files
我们对文件列表进行排序,然后遍历文件
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 )
here First thing your path is wrong it should be这里首先你的路径是错误的,它应该是
path = 'C:\\Users\\cHaTrAp\Documents\\My Games\\KillingFloor2\\KFGame\\Cache'
then to get files with .kfm extention you can also use below code然后要获取扩展名为 .kfm 的文件,您还可以使用以下代码
import os
files = os.listdir(path)
kfm_files=[f for f in files if '.kfm' in f]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.