Last active
December 14, 2018 13:53
-
-
Save jobel-code/62ba10909b3249844d896d4cec74e343 to your computer and use it in GitHub Desktop.
Different ways to read all files from a directory using python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Knowing a base `dirpath` retrieve all files starting with `NV` and with file extension `.img` | |
from glob import glob | |
onlyfiles = glob( '{}/NV*.img'.format(dirpath)) | |
# | |
import glob | |
onlyfiles = glob.glob("/home/adam/*.txt")) | |
# List recursibly in `dirpath` all the `.tif` files if `mygroup` is in filename and does not include `DEPRECIATED` | |
onlyfiles = [y for x in os.walk(dirpath) for y in glob(os.path.join(x[0], '*.tif')) if mygroup[:-2] in y and 'DEPRECIATED' not in y] | |
# | |
from os import listdir | |
from os.path import isfile, join | |
onlyfiles = [f for f in listdir(dirpath) if isfile(join(dirpath, f))] | |
# | |
from os import walk | |
f = [] | |
for (dirpath, dirnames, filenames) in walk(mypath): | |
# extending the list `f` | |
f.extend(filenames) | |
break | |
### find all the filenames in the dirpath which are files and have an extension name of `.txt` | |
[name for name in os.listdir(dirpath) if os.path.isfile(os.path.join(dirpath, name)) and '.txt' in name] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Added another example