简体   繁体   中英

glob.glob not searching through all subdirectories for .tsv files

I want to search through all of the subdirectories within a parent directory for all of the files with a .tsv extension. I have tried using the glob module but it does not return any of the subdirectory level information.

I have tried using glob.glob as a way to search through all of the subdirectories within a specific user specified location but it is not working. It simply returns an empty response, which is presumably all of the .tsv files that exist in the parent directory, which is none.

for file in glob.glob(os.path.join(location, '*.tsv')):
print(file)

What I am hoping to see is all of the .tsv files within the parent directory, even within subdirectories being printed in the shell.

You're very close. You need to use the ** character to tell glob to look in all sub-directories, and set recursive=True . Note this only works in python >= 3.5

for file in glob.glob(os.path.join(location, '**/*.tsv'), recursive=True):
    print(file)

I personally prefer the pathlib module.

from pathlib import Path
for file in Path(location).glob('**/*.tsv'):
    print(file)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM