0

I am trying to get a list of files in a directory which match a certain name e.g in Bash the Code would be :

BASH

 FOLDER="MainProject"
 FILES=`find "$FOLDER" -name "Localizations*swift"`

Python

import os

def read_files():
    path = 'MainProject/'
    folders = []
    for r, d, f in os.walk(path):
        for folder in d:
            folders.append(os.path.join(r, folder))
    for f in folders:
        print(f)

Please note I am new to python hence I am struggling with this.

oguz ismail
  • 1
  • 16
  • 47
  • 69
kaddie
  • 233
  • 1
  • 5
  • 27

2 Answers2

2

If you only need files in a single directory (no depth):

from glob import glob
import os

def read_files():
    path = 'MainProject/'
    print(list(glob(os.path.join(path, "Localizations*swift"))))

If you only need file names (and not directory names) recursively:

from fnmatch import fnmatch
import os

def read_files():
    path = 'MainProject/'
    for r, d, f in os.walk(path):
        if fnmatch(f, "Localizations*swift"):
            print(os.path.join(r, f))
Matt Shin
  • 424
  • 2
  • 7
  • This does not seem to work with Python 3.8.10, as `f` (as returned by `os.walk`) is a list of strings, whereas `fnmatch` expects a single string as its first argument. – gernot Jun 17 '22 at 15:12
0

If You want to look at the current dir:

path = 'MainProject/'
f_name = 'Localizations*swift'
all_files = os.listdir(path)
matching_files = [file for file in all_files if file==f_name]

if You want to 'walk' through the current and all subdirs, make use of the os.walk function. Also You can use some regex, to match file names

import os
for root, dirs, files in os.walk(path, topdown=False):
   for name in files:
       # if name.find(f_name)>-1: # name contains f_name
       if name==f_name:
           print(os.path.join(root, name))
Jonas
  • 513
  • 1
  • 5
  • 17