Four Tips for Mastering Python’s pathlib Module

ifeelfree
2 min readOct 25, 2023
Path from unsplash

Tips 1: search for contents in a given folder

(1) list all the contents including subfolders

import pathlib 
target_dir='/home/feifei/go/'
cnt = 0
for f in pathlib.Path(target_dir).glob("**/*"):
print(f)
cnt = cnt + 1
if cnt == 5:
break

# /home/feifei/go/pkg
# /home/feifei/go/bin
# /home/feifei/go/pkg/sumdb
# /home/feifei/go/pkg/mod
# /home/feifei/go/pkg/sumdb/sum.golang.org

(2) list certain file types:

  • we have the option to enhance this function, allowing it to exclusively search for specific types of directories or files. For example, pathlib.Path(target_dir).glob(“**/*.txt”) will only search .txt files. An alternative is to use pathlib.Path(target_dir).rglob(“*.txt)
  • list only folders: pathlib.Path(target_dir).glob(“**”) will only search folders and subfolders within the target directory.

(3) list files/directories in the current folder:

import pathlib 
target_dir='/home/feifei/go/'
cnt = 0
for f in pathlib.Path(target_dir).glob("*"):
print(f)
cnt = cnt + 1
if cnt == 5
# /home/feifei/go/pkg
# /home/feifei/go/bin

We can list certain types of files by: pathlib.Path(target_dir).glob(“*.txt”)

--

--