The pathlib
module uses an object-oriented approach to deal with the filesystem in a platform-agnostic and intuitive manner. The module was first introduced in Python 3.4.
Here, we will learn how to use the pathlib
module with examples.
A path object can be created by passing the path string as a parameter while in object creation:
new_path = Path("/users/john/Docs")
new_path.exists()
new_path = Path("/usr/abhi/Docs/hello.py")
print(new_path.name)
new_path = Path("kib.yaml")
print(new_path.suffix)
If there is more than one extension, then use .suffixes
:
new_path = Path("file.tar.gz")
print(new_path.suffixes)
new_path = Path("/Users/abhi/Downloads/MatterHorn/documentation/img/top_no_dm.gif")
print(new_path.parent)
To get all the ancestors, use .parents
:
print(list(new_path.parents))
print(new_path.is_file())
# OR
print(new_path.is_dir())
new_path = Path("/Users/abhi/Downloads/UMatter/documentation/img")
print(new_path.stat())
print(Path.cwd())
new_path = Path("/Users/abhi/Downloads/UMatter/documentation/img")
print(list(new_path.glob("*.gif")))
new_path = Path("/Users/abhi/Downloads/dir1/dir2/hello_world.py")
new_path.mkdir(parents=True)
new_path = Path("/Users/abhi/Downloads/UMatter/documentation/img")
print(list(new_path.iterdir()))
path1 = Path("/Users/abhi/Downloads")
path2 = Path("dir1/dir2/hello_world.py")
print(path1.joinpath(path2))
new_path = Path("hello_world.py")
print(new_path.absolute())
new_path = Path("/Users/abhi/Downloads/dir1/dir2/a.txt")
print(new_path.read_text())
new_path = Path("/Users/abhi/Downloads/dir1/dir2/b.txt")
new_path.write_text("hello educative")