Use multiple file extensions for glob to find files

社会主义新天地 提交于 2019-12-23 13:15:23

问题


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)

回答1:


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))


来源:https://stackoverflow.com/questions/47840320/use-multiple-file-extensions-for-glob-to-find-files

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!