使用glob的多个文件扩展名查找文件 [英] Use multiple file extensions for glob to find files
本文介绍了使用glob的多个文件扩展名查找文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用glob通过此代码行列出主目录中的所有python文件. 我也想同时找到所有.json文件和py文件,但找不到任何要在一行代码中扫描多种文件类型的文件.
I am using glob to list out all my python files in the home directory by this line of code. I want to find all .json files too along with py files, but I couldn't found any to scan for multiple file types in one line code.
for file in glob.glob('/home/mohan/**/*.py', recursive=True):
print(file)
推荐答案
You could use os.walk, which looks in subdirectories as well.
import os
for root, dirs, files in os.walk("path/to/directory"):
for file in files:
if file.endswith((".py", ".json")): # The arg can be a tuple of suffixes to look for
print(os.path.join(root, file))
这篇关于使用glob的多个文件扩展名查找文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文