Issue
I have the following code
os.chdir("X:\data1")
for file in glob.glob("*.pdf"):
to find all the .pdf
files in X:\data1\
directory
I would like to also find all the .txt
file in Y:\data2\
directory
I have this snippet in multiple places in the source code, so I would like to make only a little change.
Solution
Would something like this do?
import os
import glob
def ignore_case(pattern):
return ''.join((f'[{c.lower()}{c.upper()}]' if c.isalpha() else c for c in pattern))
def multi_glob(patterns):
for path, pattern in patterns:
yield from glob.iglob(os.path.join(path, ignore_case(pattern)))
list(multi_glob((("X:\data1", "*.pdf"), ("Y:\data2", "*.txt"))))
Essentially, instead of os.chdir(path); glob.glob(pattern)
you could just do glob.glob(os.path.join(path, pattern))
.
If you you want this to happen for multiple path/pattern combinations, you could just have a loop through them.
Finally, to get case insensitive patterns, just replace each letter c
of the pattern with [cC]
.
Answered By - norok2
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.