Check whether files exist, build paths that work on every system, and take paths apart with os.path and pathlib.
import os
# check if exists
os.path.exists("file.txt")
# ans: True or False
# check if file
os.path.isfile("file.txt")
# ans: True or False
# check if directory
os.path.isdir("folder")
# ans: True or False
import os
# file size
os.path.getsize("file.txt")
# ans: size in bytes
# absolute path
os.path.abspath("file.txt")
# ans: /full/path/to/file.txt
abspath glues the current working directory onto a relative path.
import os
# join paths
os.path.join("folder", "file.txt")
# ans: folder/file.txt
# ans: works across platforms
import os
# directory name
os.path.dirname("/path/to/file.txt")
# ans: "/path/to"
# base name
os.path.basename("/path/to/file.txt")
# ans: "file.txt"
# split extension
os.path.splitext("file.txt")
# ans: ("file", ".txt")
from pathlib import Path
# create path object
path = Path("file.txt")
# check exists
path.exists()
# ans: True or False
# read file
content = path.read_text()
A Path is an object with methods, instead of a plain string passed to os.path functions.
from pathlib import Path
path = Path("/folder/file.txt")
# name
path.name
# ans: "file.txt"
# stem
path.stem
# ans: "file"
# suffix
path.suffix
# ans: ".txt"
# parent
path.parent
# ans: Path("/folder")
pathlib names on top, the matching os.path function underneath. os.path.splitext splits off the same suffix, which is only the last extension.
Predict, then reveal.
import os
# exists vs isfile?
os.path.exists("folder")
# ans: True
os.path.isfile("folder")
# ans: False
import os
# join paths?
os.path.join("a", "b", "c")
# ans: "a/b/c" (or "a\\b\\c" on Windows)
import os
# splitext?
os.path.splitext("file.tar.gz")
# ans: ("file.tar", ".gz")
from pathlib import Path
# path / operator?
Path("folder") / "file.txt"
# ans: Path("folder/file.txt")
from pathlib import Path
# suffix with no extension?
Path("file").suffix
# ans: ""
import os
# abspath on absolute?
os.path.abspath("/a/b/c")
# ans: "/a/b/c" (unchanged)
from pathlib import Path
# multiple suffixes?
Path("file.tar.gz").suffixes
# ans: [".tar", ".gz"]
import os
# basename of directory?
os.path.basename("/path/to/")
# ans: ""
os.path.basename("/path/to")
# ans: "to"
basename is just the text after the last slash, so a trailing slash leaves nothing.
from pathlib import Path
# parent of parent?
Path("/a/b/c").parent.parent
# ans: Path("/a")
import os
# current directory?
os.getcwd()
# ans: returns current working directory
exists is True for files and folders; isfile and isdir tell them apart.
os.path.join or Path(...) / "name" pick the right separator for the system.
parent/dirname, name/basename, stem and suffix/splitext.
Relative paths start from os.getcwd(); abspath makes them absolute.