How to get all files in a directory and delete them?


Obtain all files in a pathlib.Path directory and delete them


If we have a directory as a Path object we can call .iterdir() on it to obtain a generator that will yield all files present in that directory as Path objects. And if we want to delete all files in a given directory we can .unlink on every Path object returned by iterdir(). Using missing_ok=True is to avoid any race-conditions.


Github gist with code

dependencies: python3.9

Comments