-
Notifications
You must be signed in to change notification settings - Fork 7
Path management
Use of the pathlib library instead of os.path to manage path.
- Less verbose
- Object-oriented with a set of useful attributes
- Better readability
- Works everywhere, compatible with the os module
- More pythonic
- Less used/known
Path("path","to","somewhere") : Create a path object. Without argument, return the current workind directory (analog to os.getcwd())
Path("root").joinpath("subpath","subsubpath") : Extend a path object and return a new path. Analog to os.path.join("root","subpath","subsubpath").
Path("root").glob("*.txt") : Search in the path for files matching the pattern. A better alternative to the glob library. Can also search recursively using rglob().
Path("root","folder").mkdir() : Refer to make_path
path = Path("root","subpath","file.txt")
print(path.name) #=> file.txt
print(path.stem) #=> file
print(path.suffix) #=> .txt
print(path.parent) #=> Path("root","subpath")
print(path.exists()) #=> True if the path existsos.path should be banned, but the os module still has useful functions:
os.listdir() vs Path().iterdir() : The former returns the content of a directory as a list whereas the latter returns a generator. A generator yields items one by one and does not have a len() property, but is lighter in memory.