Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find file in folder without knowing the extension?

Let's say I want to search for a file name "myfile" in a folder named "myfolder", how can I do it without knowing the format of the file? Another question: how to list all files of a folder and all the files of it's subfolders (and so on)? Thank you.

like image 342
Kazama Avatar asked Oct 26 '25 03:10

Kazama


2 Answers

import os
import glob
 
path = 'myfolder/'
for infile in glob.glob( os.path.join(path, 'myfile.*') ):
    print "current file is: " + infile

if you want to list all the files in the folder, simply change the for loop into

for infile in glob.glob( os.path.join(path) ):
like image 191
Samuele Mattiuzzo Avatar answered Oct 28 '25 15:10

Samuele Mattiuzzo


To list all files in a folder and its subfolders and so on, use the os.walk function:

import os
for root, dirs, files in os.walk('/blah/myfolder'):
    for name in files:
        if 'myfile' in name:
            print (f"Found {name}")

In the easier case where you just want to look in 'myfolder' and not its subfolders, just use the os.listdir function:

import os
for name in os.listdir('/blah/myfolder'):
    if 'myfile' in name:
        print (f"Found {name}")
like image 24
André Laszlo Avatar answered Oct 28 '25 15:10

André Laszlo