Paths
A path is a name for a location in a file system.
"data/scores.txt"
This path says: look for scores.txt inside the data folder.
Relative paths
A relative path is interpreted from the current working directory:
The path "scores.txt" means “a file named scores.txt in the current working
directory.”
You can inspect the current working directory with pathlib:
Current working directory
Ready to run.
Path("data") / "scores.txt" builds a path without hard-coding a slash. This
is clearer and works across operating systems.
Absolute paths
An absolute path starts from a file-system root rather than the current working directory. Its written form differs across operating systems. You can inspect an absolute location without hard-coding one:
Prefer relative project paths when the data travels with the project. Use an absolute path when the location is intentionally tied to one machine, and do not paste a path from someone else's computer into your program unchanged.
Create a folder before writing inside it
If a folder does not exist, writing a file inside it fails:
Create the folder first:
exist_ok=True means “do not fail if this folder already exists.”
Paths are not contents
A path names a place. It is not the text inside the file.
path = Path("scores.txt")
This creates a path object. It does not read the file. To read, open the path:
What expression builds the path data/scores.txt using Path and /?
Select one choice, then check.
HintStart with a Path object
The / path-joining behavior is provided by Path, not by two plain strings.
SolutionJoin the folder and filename
Path("data") / "scores.txt" creates the required path object. It does not
read or write the file yet.