Stack Overflow Asked on December 27, 2021
For example in the my_dir structure folder there are 4 files:
I want my function to return only files that look like fname, so the README.md, readme.md and my_ReadMe.md
from glob import glob as gl
fname = 'readme.md'
my_dir = '/my_dir'
files = gl(f'{my_dir}/**/{fname}', recursive=True)
if files:
# do stuff
Assuming that you are looking to match all .md
files that "look like" - defined here as containing the sub-string readme
(case insensitive) - from within the directory specified by my_dir
and all sub-directories contained within, the following should work for you.
import glob
import os
my_dir = 'my_dir' # IMPORTANT Please note that the leading '/' has been removed, this is to allow for desired behaviour in os.path.join() below
files = [ i for i in glob.glob(os.path.join(my_dir, '**', '*.md'), recursive=True) if 'readme' in os.path.basename(i.lower()) ]
if files:
# do stuff
It makes use of the builtin os
module to construct the path passed to glob.glob
that will search the top-level directory passed as the my_dir
variable recursively and return all paths ending with a .md
file.
The list of .md
file paths returned by the invocation of glob.glob
is filtered (by way of a list comprehension) to only include paths ending in .md
files containing the sub-string readme
(case insensitive).
The result is a list of all paths from within the my_dir
tree that end in an .md
file containing the case insensitive sub-string readme
within the filename portion of the path - or an empty list if none are found.
Answered by JPI93 on December 27, 2021
Loop through the list of files in your directory and compare with re.search:
import re
files=['README.md','readme.md','my_readme.md','what.md']
query='readme.md'
print([file for file in files if re.search(query , file, re.IGNORECASE)])
Answered by Alex S on December 27, 2021
Get a list of all file names source
from os import listdir
from os.path import isfile, join
files = [f for f in listdir(mypath) if isfile(join(mypath, f))]
Loop through each file name, and check if the lowercase version includes fname
for name in files:
if fname in name.lower():
print(name)
If you want to find all files, then looking at the link i provided earlier you can find the following code to find all files:
from os import walk
files = []
for (dirpath, dirnames, filenames) in walk(mypath):
files.extend(filenames)
Answered by dantechguy on December 27, 2021
Get help from others!
Recent Questions
Recent Answers
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP