7.3 Paths and Encoding
The most common file problems do not always come from read() or write(). They often come from paths and encoding. A path tells Python where to find a file; encoding tells Python how to interpret the bytes inside a text file.
Relative Paths and the Current Working Directory
A relative path is not automatically relative to the Python file. It is relative to the current working directory.
with open("data/quotes.txt", "r", encoding="UTF-8") as file:
content = file.read()If the current working directory is the project root, Python looks for:
project/
data/
quotes.txtBut if you run the program from another directory, the same "data/quotes.txt" may not be found.
FileNotFoundError, first check where the program is starting its file search.UTF-8 Encoding
Text files store bytes. Encoding converts between characters and bytes. UTF-8 is one of the most common and compatible text encodings.
with open("note.txt", "w", encoding="UTF-8") as file:
file.write("Hello, Python!")
with open("note.txt", "r", encoding="UTF-8") as file:
print(file.read())If writing and reading use different encodings, plain English may appear fine, but non-English text and symbols can break.