Search
In your solution, you will have to go through all files stored in directories:
There is more ways to achieve this; we shall list here some of them.
Function listdir() (docs) from os module returns a list of filename from specified directory. If we have the following directory with files
listdir()
os
+- train_data +- truth.dsv +- img112.png +- img113.png +- img114.png
import os for fname in os.listdir("train_data"): print(fname)
img_1112.png img_1113.png img_1114.png truth.dsv
You can also use similar function os.scandir() which returns a generator.
If you like object-oriented interfaces better, then you can use class Path and its method iterdir() (docs):
Path
iterdir()
from pathlib import Path path = Path("train_data") for fpath in path.iterdir(): print(fpath)
After running the above script:
train_data\img_1112.png train_data\img_1113.png train_data\img_1114.png train_data\truth.dsv
Generator iterdir() returns instances of Path class which encapsulate the paths to individual files. But you can easily use these objects when opening files using open() function.
open()
More examples how to use pathlib can be found in this nice pathlib tutorial.
pathlib