Working with text and files
Paths and text files
Use pathlib to write and read a UTF-8 text file in a known location.
Lesson 30 of 63
Reading: about 2 min
Lesson + practice: about 14 min
Difficulty: Beginner
On this page4 sections
A path points to a file or directory. pathlib.Path joins path parts in a way that works across operating systems. A relative path such as notes.txt is relative to the current working directory when you run the program.
For file practice, download the Python practice files v1.0.0 bundle. The examples write their own files, so the samples stay unchanged. Work on a copy if you edit a sample.
from pathlib import Path
notes = Path("my_notes.txt")
notes.write_text("Practice Python today.\n", encoding="utf-8")
print(notes.read_text(encoding="utf-8").strip())Practice Python today.
Appending without replacing
write_text() replaces an existing file. To add text to the end instead, open the file in append mode with a with block. The with block closes the file afterward.
from pathlib import Path
notes = Path("my_notes.txt")
notes.write_text("First note\n", encoding="utf-8")
with notes.open("a", encoding="utf-8") as file:
file.write("Second note\n")
print(notes.read_text(encoding="utf-8").splitlines())['First note', 'Second note']
Why this works
Path("my_notes.txt") uses the process’s current working directory, which is usually the folder you entered in the terminal before running Python. It is not automatically the folder where the .py file lives. write_text() replaces file contents; opening with "a" appends to existing contents.
Practice
Create a practice text file with two lines. Read it back using UTF-8 and print the lines. Check the file in your project folder. Then read the sample notes.txt from the practice bundle with read_text(encoding="utf-8") and print its lines.
What does Path("my_notes.txt") refer to?
Reveal answer
A relative path named my_notes.txt in the program’s current working directory.
Try another case
If my_notes.txt contains "old" and write_text("new") runs, what remains in the file?
Check your answer
Reveal answer
Only "new" remains, because write_text() replaces the file contents.
Your progress
Reveal the check answer or reach the end to complete this lesson.