How to get directories/files in Python

data/
train/
1.txt
2.txt
3.txt
test/
1.txt
2.txt
3.txt

os.listdir

import os

in_dir = './data'
for dirname in os.listdir(in_dir):
print(dirname)
train
test
import os

in_dir = './data'
for dirname in os.listdir(in_dir):
print(os.path.join(in_dir, dirname))
./data/train
./data/test

glob.glob

import glob

for filename in glob.glob('./data/train/*.txt'):
print(filename)
./data/train/1.txt
./data/train/2.txt
./data/train/3.txt
import glob

for filename in glob.glob('./data/*/*.txt'):
print(filename)
./data/train/1.txt
./data/train/2.txt
./data/train/3.txt
./data/test/1.txt
./data/test/2.txt
./data/test/3.txt

Conclusion

--

--

--

Machine Learning Engineer / Youtube streamer. I will share useful information about engineering.

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Cassava’s AfriMyth is a composable NFT collection that celebrates our African heart.

NEWINU — Video Competition, Elon Musk birthday🏆

How to Install Python 3 on Mac M1 (with pyenv)

Latest Development

System Design Must-Haves

Django Logging

How to Export Movie Ratings from Netflix and Import into IMDb

Debugging LLVM with lldb python plugin

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
pillyshi

pillyshi

Machine Learning Engineer / Youtube streamer. I will share useful information about engineering.

More from Medium

Choosing names with Python

Insertion Sort In Python

CRUNCH COUNTER IN PYTHON