Using pathlib.Path.glob¶
This is the easiest way to iterate through all descendant files of a directory in Python.
In [1]:
from pathlib import Path
In [11]:
paths = Path("cn").glob("**/*")
[path for path in paths if path.is_dir()][:20]
Out[11]:
In [12]:
paths = Path("misc").glob("**/*")
[path for path in paths if path.is_file()][:20]
Out[12]:
Using os.walk¶
In [3]:
import os
for subdir, dirs, files in os.walk("."):
for file in files:
filepath = os.path.join(subdir, file)
if filepath.endswith(".csv"):
print(subdir)
print(dirs)
print(filepath)
Or you can implement it yourself using Path.iterdir()
.
In [ ]: