4

我正在使用 glob 通过这行代码列出我在主目录中的所有 python 文件。我也想找到所有 .json 文件以及 py 文件,但是我找不到任何可以在一行代码中扫描多种文件类型的文件。

for file in glob.glob('/home/mohan/**/*.py', recursive=True):
    print(file)
4

1 回答 1

5

您可以使用os.walk,它也在子目录中查找。

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))
于 2017-12-15T22:43:06.687 回答