Python Files
note.txt is a name on the computer. The letters inside it stay there after the program has finished. open is how this program reaches that name. The first program puts one short line in the file. The second reads that line back. On this page you write close yourself. The next page still closes the file when a line stops before close.
note = open("note.txt", "w", encoding="utf-8")
note.write("tea\n")
note.close()
The screen stays empty, because this program never prints. write places the letters tea in note.txt, and \n ends the line. Mode w creates note.txt when that name is missing. If the file already holds other words, w drops them. After this write, the file holds only tea and the line break. close is what finishes the storing. Before close, do not count the line as saved. encoding="utf-8" means the letters are stored as text.
📊 Two ways to open
| Mode | What that open does |
|---|---|
| w | creates note.txt if it is missing, and replaces whatever was inside |
| r | reads note.txt; if the file is missing, the program stops with FileNotFoundError |
note = open("note.txt", "r", encoding="utf-8")
text = note.read()
note.close()
print(text)
This program starts on its own and does not write. tea has to be in note.txt already, from the first program. read() gives back every character as one string, and the line break is part of that string. print shows tea, then a blank line. The string already ends with a line break, and print adds one more. close runs again, so the read is finished. The same encoding="utf-8" is there so the letters come back as text.
Open that name with r while note.txt is not on the machine, and the program stops. The name of the stop is FileNotFoundError. Those lines are not in the programs here. w would create the file instead of stopping. Python does not invent empty text and keep going.
close on this page is a line you write when you are done. The next page uses with, so the file still closes when a line stops before close. These programs do not use with.
What landed in the file
The first screen is empty, and after close the file holds tea. Mode w replaces older words. The second screen shows tea, then a blank line. Opening a missing file with r stops the program. The next page closes the file even if a line stops.
🧠 Test Your Knowledge
Test Your Knowledge
Challenge yourself with this interactive quiz and see how well you understand the topic
📝 Instructions
- Read each question carefully
- Select the best answer for each question
- You can retake the quiz as many times as you want
- Your progress will be shown at the top