Reading and Writing Text Files
When a program ends, the data in its variables disappears. We learn to store data permanently by writing to a file and reading from it.
All topics (11 of 11)
Chapter 1. Python Basics
Chapter 2. Lists and Strings
Chapter 3. Functions and Modules
Chapter 4. Working with Files
Variables live in the computer’s memory and vanish when the program ends. To keep data for a long time, we have to write it to a file. A text file is a file that holds plain text (for example notes.txt) and can be opened in any editor. Python works with files through the open() function.
Working with a file has three stages: open, read or write, close. The most convenient way is the with construction: with open("notes.txt", "w", encoding="utf-8") as f: and inside it f.write("Salom\n"). When the block ends, the file closes itself. The mode letter matters: "r" is reading, "w" is writing (old content is erased), "a" is appending to the end.
There are several ways to read a file. f.read() returns the whole text as one string, f.readline() reads one line, and f.readlines() returns a list of lines. The simplest way is to loop over the file: for line in f: and print(line.strip()). The strip() method removes the invisible newline character at the end.
If the file being read does not exist, Python raises a FileNotFoundError. It can be caught with try and except FileNotFoundError: to show the user a clear message. Make it a habit to give encoding="utf-8" so that Uzbek letters are saved correctly. When writing numbers to a file, convert them to strings with str().
Key takeaways
- Data written to a file is kept even after the program ends.
with open(name, mode, encoding="utf-8") as f:is a convenient way to work with a file.- Modes:
"r"read,"w"write,"a"append. - A missing file raises
FileNotFoundError; it can be caught withtry/except.
Practice tasks
- Write a program that asks for a name and appends it to the file
names.txtin"a"mode; run it three times. - Read the file
names.txtline by line and print each name with its sequence number. - Create a program that counts the lines in a file; if the file is not found, print “File not found” (
try/except).
Review questions
Test yourself: think first, then reveal the answer.
1How do the `"w"` and `"a"` modes differ?Show answerHide answer
`"w"` erases the old content and writes anew, while `"a"` adds to the end of the existing content.2Why is `with open(...)` convenient?Show answerHide answer
The file closes automatically when the block ends, so there is no risk of forgetting to close it.
0 of 11 topics completed
Sign in to mark