Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to open files that match a pattern in a subdirectory

Tags:

python

Hello i have a problem finding and opening files in a subdirectory. I have several different files called for example :
mouse_1_animal.txt
mouse_2_animal.txt mouse_3_animal.txt

so i want to find all these files in the subdirectory of the working dir and open them and do something with there lines. This is my try:

i=1
for path, subdirs, files in os.walk(root) :
    for file in files :
        if file == "mouse_{0}_animal.txt".format(i) :
            #do something
            i = i + 1

but apparently it doesn't find all the files so i'm wondering if it's the way i'm using to find the file that is wrong.

like image 756
steT Avatar asked Oct 16 '25 18:10

steT


1 Answers

The pythonic way:

import glob
for f in glob.glob('./subDir/mouse_*_animal.txt'):
    # do_something
like image 124
haavee Avatar answered Oct 18 '25 11:10

haavee