# Python pathlib: Traverse Files in a Directory – Python Tutorial

By | July 6, 2021

In this tutorial, we will use some examples to show you how to traverse files in a directory using python pathlib library.

Here are also other ways to traverse files in python, they are:

Python Traverse Files in a Directory for Beginners

Python Traverse Files in a Directory Using glob Library: A Beginner Guide

## Traverse files not in subdirectory

For example, we will get all .py files in current directory, we can do as follows:

import pathlib

def getFiles(path='.', filetype = ".py"):
files = pathlib.Path(path).glob('*'+filetype)
for px in files:
print(px)
with open(px, 'r') as f:
getFiles()

Run this code, you will get this result:

loss.py
attlayer.py
model_bilstm_cnn_word2vec.py
fileutil.py

However, if we also want to get all .py files that are in subdirectories? How to do?

## Traverse files that are in subdirectories

We can use code example to implement it.

import pathlib

def getFiles(path='.', filetype = ".py"):

files = pathlib.Path(path).glob('**/*'+filetype)
for px in files:
print(px)

getFiles()

Run this code, we will get all .py files in current directory.

Here is a list:

attlayer.py
model_bilstm_cnn_word2vec.py
fileutil.py
data_prepare/intent_train_data_prepare.py
data_prepare/intent_reason_train_data_prepare.py
data_intent_prepare/intent_train_data_prepare.py