File Paths and open()
In this tutorial, we'll understand file paths, modes, and the open() function.
Python can read and write files on your computer.
To work with a file, you usually use open():
file = open("notes.txt", "r")
The first argument is the file path. The second argument is the mode.
File Paths
A path tells Python where a file is.
"notes.txt"
"data/scores.txt"
"notes.txt" means a file in the same folder as your Python program.
"data/scores.txt" means a file called scores.txt inside a folder called data.
File Modes
Common modes:
| Mode | Meaning | | --- | --- | | "r" | Read an existing file | | "w" | Write a file, replacing old content | | "a" | Append to the end of a file |
Be careful with "w". It replaces the file contents.
Prefer with
Use with when opening files:
with open("notes.txt", "r") as file:
content = file.read()
print(content)
with closes the file automatically when the block ends.
Text Files
These beginner lessons focus on text files, such as .txt, .csv, or simple log files. Text files contain readable characters.
Other file types, such as images or PDFs, need different techniques. Start with text files first because they are easier to inspect and understand.
Practice
Create a text file called notes.txt beside your Python file. Open it in read mode and print its contents.