我想在父目录中的所有子目录中搜索具有.tsv
扩展名的所有文件。我尝试过使用glob模块,但它没有返回任何子目录级别的信息。
我曾尝试使用glob.glob作为搜索特定用户指定位置中的所有子目录的方法,但它不起作用。它只是返回一个空响应,该响应可能是父目录中存在的所有.tsv
文件,即none。
for file in glob.glob(os.path.join(location, '*.tsv')):
print(file)
我希望看到的是父目录中的所有.tsv
文件,甚至在shell中打印的子目录中也是如此。
发布于 2019-10-23 12:37:22
你已经很接近了。您需要使用**
字符告诉glob查看所有子目录,并设置recursive=True
。请注意,这只适用于python >= 3.5
for file in glob.glob(os.path.join(location, '**/*.tsv'), recursive=True):
print(file)
我个人更喜欢pathlib模块。
from pathlib import Path
for file in Path(location).glob('**/*.tsv'):
print(file)
https://stackoverflow.com/questions/58518187
复制