Part One
What Is a File Path?
A file path is just the location of a file. When you write "notes.txt", Python looks for a file called notes.txt in the current folder.
| Path | Meaning |
|---|---|
"notes.txt" |
A text file in the same folder as your program. |
"data/notes.txt" |
A file inside a folder called data. |
"todo.txt" |
Another simple file name. The .txt ending means plain text. |
"notes.txt".
Part Two
Saving Text with open()
To save text to a file, use open(path, mode). The path is the file name. The mode tells Python what you want to do with the file.
"w"means write: create the file or replace its contents"r"means read: open an existing file"a"means append: add new text at the end
file.write(...) sends text into the file. file.close() closes the file so Python finishes saving it.
You can also write files with with open(...). This is a shorter pattern that closes the file automatically when the block ends.
with open()"w" mode will overwrite the old contents. With with open(...), you do not need to write file.close().
Part Three
Opening and Reading a Text File
To read a file, open it in "r" mode and then use .read().
.read() returns the whole file as one string. If the file has line breaks, they come back inside that string too.
You can read a file with with open(...) too.
with open()Part Four
Appending More Text
If you want to add text without deleting what is already there, use "a" mode.
The second line is added at the end because the file was opened in append mode.
Part Five
Your Turn
Create a file called journal.txt. Save three lines of text into it, then open it again and print the contents.
open(). That is a strong base for everything that comes next.
Chapter Navigation
Move between chapters.