pathlib

The better core filesystem lib in python!

Import with

from pathlib import Path

Editing Paths

fp=Path(r"C:\temp\images\myfile.png")

print( fp.name )
# > "myfile.png"
print( fp.stem )
# > "myfile"
print( fp.suffix )
# > ".png"
print( fp.drive )
# > "C:"
print( fp.anchor )
# > "C:\"
print( fp.parent )
# > "C:\temp\images"
print( fp.parent[0], fp.parent[1] ) # and so on...
# > "C:\temp\images", "C:\temp" ...

# CAREFUL!
fp=Path("MyMultySuffixFile.png.meta")
print(fp.stem)
# > "MyMultySuffixFile.png" <= still has another suffix

# reading/writing
with fp.open() as f: 
    f.readline()
f.write_text("My Text")
wot

# workaround
def true_stem(path):
   stem = Path(path).stem
   return stem if stem == path else true_stem(stem)

# iterating
for f in path.iterdir():
    print(f)

print(true_stem(fp))
# > "MyMultySuffixFile"

Reading/Writing

Function Read Write
Bytes Path.read_bytes() Path.write_bytes(data)
Text Path.read_text(
encoding=None, errors=None)
Path.write_text(
data, encoding=None, errors=None, newline=None)

Various functions

Function Description
Path.resolve() Make the path absolute, resolving any symlinks.
A new path object is returned
Path.chmod() Change the file mode and permissions
Path.mkdir() Make Directory
Path.rename() Rename File
Path.replace(target) Rename this file or directory to the given target,
and return a new Path instance pointing to target.
Path.rmdir() Remove this directory. The directory must be empty.
Path.unlink() Delete this file or remove the symbolic link.
If the path points to a directory,
use Path.rmdir() instead.
Path.cwd() Return a new path object
representing the current directory
(change working dir)
Path.exists() Whether the path points to an existing file or directory
Path.expanduser() Return a new path with expanded ~ and ~user constructs
Path.home() Return a new path object representing
the user’s home directory
Path.iterdir() When the path points to a directory,
yield path objects of the directory contents
Path.glob(pattern)
Path.rglob(pattern)
Glob the given relative pattern
in the directory represented by this path
RGlob also looks in sub paths
Path.is_dir() Is this path a dir?
Path.is_file() Is this path a file?
Path.is_symlink() Is this path a symlink?
Path.symlink_to(target, is_dir) Make a symlink
Path.readlink() Return the path to which the symbolic link points
Path.stat()
Path.owner()
Path.group()
Information about this path,
name of the user or the group owning the file
PurePath.is_absolute() Return whether the path is absolute or not.
PurePath.is_relative_to(*other) Return whether or not this path is relative to the other path.
PurePath.joinpath() combining the path with each of the other arguments
PurePath.parent The logical parent of the path:
Path.samefile(other_path) Return whether this path points to the same file as other_path
PurePath.suffix The file extension of the final component, if any:
'.py'

Examples / Tipps

Print all paths

for p in src.iterdir():
    if not p.is_dir():
        continue
    print(p)

Copy a file. Can also be done with winshell lib.

import pathlib
import shutil

my_file = pathlib.Path('/etc/hosts')
to_file = pathlib.Path('/tmp/foo')

shutil.copy(str(my_file), str(to_file))  # For Python <= 3.7.
shutil.copy(my_file, to_file)  # For Python 3.8+.

For creating a shortcut in windows, you need the winshell lib:

def create_shortcut(link_dir, link_destination):
    """Takes two pathlib paths, creates a shortcut in the first to the destination"""
    link_filepath = str(link_dir / (link_dir.stem + ".lnk")) # str because pathlib
    with winshell.shortcut(link_filepath) as link:
        link.path = str(link_destination)
        link.description = link_destination.stem
        link.arguments = ""