How do I list all files of a directory?

os.listdir() returns everything inside a directory — including both files and directories. os.path‘s isfile() can be used to only list files: from os import listdir from os.path import isfile, join onlyfiles = [f for f in listdir(mypath) if isfile(join(mypath, f))] Alternatively, os.walk() yields two lists for each directory it visits — one for files and … Read more

How can I safely create a nested directory?

On Python ≥ 3.5, use pathlib.Path.mkdir: from pathlib import Path Path(“/my/directory”).mkdir(parents=True, exist_ok=True) For older versions of Python, I see two answers with good qualities, each with a small flaw, so I will give my take on it: Try os.path.exists, and consider os.makedirs for the creation. import os if not os.path.exists(directory): os.makedirs(directory) As noted in comments … Read more