DEV Community

chris48s
chris48s

Posted on • Originally published at chris48s.github.io

Three useful pathlib snippets

from pathlib import Path
p = Path('/foo/bar')


# Read in a text file
text = (p / 'file.txt').read_text()

# Recursively list all .csv files in directory
csvs = list(p.rglob('*.csv'))

# Iterate files or subdirectories
files = [i for i in p.iterdir() if i.is_file()]
subdirs = [i for i in p.iterdir() if i.is_dir()]
Enter fullscreen mode Exit fullscreen mode

Top comments (0)