ይህ ትምህርት ገና ወደ አማርኛ አልተተረጎመም፤ ስለዚህ በእንግሊዝኛ ቀርቧል። የእንግሊዝኛውን ገጽ ክፈቱ
Reading and writing files
The contact book from lesson 4.9 forgets everything the moment it ends: its dict lives only while the program runs. A file fixes that. By the end of this lesson you'll write text to a file, read it back, add to it without losing what's there, and handle a file that doesn't exist yet.
Writing and reading a file
A
keeps text after the program that wrote it has ended. This program writes two lines to
notes.txt, then reads the file back:
with open("notes.txt", "w", encoding="utf-8") as f:
f.write("ቡና 25\n")
f.write("ሻይ 10\n")
with open("notes.txt", encoding="utf-8") as f:
text = f.read()
print(text)In the editor, press Escape then Tab to move on.
Run it and open Files: notes.txt is marked new, with both lines in it. The empty
line at the end of the output is the file's last \n, followed by the one print adds.
open() takes the file's name, a
,
and an
.
"w" means write. With no mode, as in the second open(), the mode is "r", read.
The encoding is the rule from lesson 6.3 for turning characters into bytes; "utf-8"
saves Amharic correctly.
The
statement does the rest: open() opens the file, as f names the open file f for
the indented block, and when the block ends, with closes it. f.write() writes exactly the
text you give it and nothing more, so each line needs its own \n. f.read() returns
the whole file as one string.
Write, or add?
This time notes.txt already has two lines (shown under the code). Predict what this
prints:
ውጤቱን ገምቱ
Decide before you look. Guessing wrong is how this sticks.
with open("notes.txt", "w", encoding="utf-8") as f:
f.write("three")
with open("notes.txt", encoding="utf-8") as f:
print(f.read())Also in the folder with main.py:
notes.txt
one two
Python prints
three
"w" empties the file the moment it opens it, before anything is written. Only "three" is left.
If you picked the first answer, you read "write" as "add". If you picked the last, you
pictured the new text replacing only the first line. In fact, "w" empties the whole
file as soon as it opens it, before anything is written. That's what you want for saving a fresh copy, and a disaster for
a log you meant to keep.
To add to the end, open with "a", append:
with open("notes.txt", "a", encoding="utf-8") as f:
f.write("three\n")
with open("notes.txt", encoding="utf-8") as f:
print(f.read())In the editor, press Escape then Tab to move on.
ፋይሎች1 starting file
notes.txt
one two
"w" and "a" both create the file if it doesn't exist. Change "a" to "w" and run
it again to see the difference in Files.
ጥያቄ
Which mode adds a line to a log without losing the old lines?
Reading line by line
A file isn't a list you can read again and again. Predict:
ውጤቱን ገምቱ
Decide before you look. Guessing wrong is how this sticks.
with open("notes.txt", encoding="utf-8") as f:
first = f.read()
second = f.read()
print(repr(first))
print(repr(second))Also in the folder with main.py:
notes.txt
one two
Python prints
'one\ntwo\n' ''
An open file keeps a position. The first read() goes to the end, so the second has nothing left and returns an empty string.
If you expected the text twice, you pictured the file like a list. An open file keeps a
position: reading moves it forward, and after the first read() it's at the end. To
read again, open the file again.
readlines() reads every line into a list, and the first line of output below shows
that each line keeps its \n. To work with the lines one at a time, loop over the file
instead; the lines keep their \n there too, so strip() each one (lesson 6.1):
with open("visitors.txt", encoding="utf-8") as f:
print(f.readlines())
with open("visitors.txt", encoding="utf-8") as f:
for line in f:
print(line.strip())In the editor, press Escape then Tab to move on.
ፋይሎች1 starting file
visitors.txt
Hana Abel Selam
Closing, and files that aren't there
with closes the file even when an error happens inside the block, like finally from
lesson 7.2. Here int() fails, and the file is closed anyway (f.closed is True once
a file is closed):
try:
with open("count.txt", encoding="utf-8") as f:
count = int(f.read())
except ValueError:
print("Not a number")
print(f.closed)In the editor, press Escape then Tab to move on.
ፋይሎች1 starting file
count.txt
twelve
A file you never close may not have all its text saved, and other programs may not be
able to use it. With with, you can't forget.
Reading a file that doesn't exist is the first error every program with files meets:
Why encoding="utf-8" every time? Without it, Python uses the computer's default
encoding. On macOS and Linux that's UTF-8, but on Windows, up to Python 3.14, it's
usually an older one that has no Ge'ez letters: writing Amharic stops with a
UnicodeEncodeError, and reading a UTF-8 file usually stops with a UnicodeDecodeError
(or shows garbage). Python 3.15, due in
October 2026, makes UTF-8 the default everywhere, but writing it yourself works on
every version and every computer.
መልመጃ
A visitor log
visitors.txt already has two names. Ask for a name, add it to the end of the file,
then print every name in the file, one per line. The Input box has Selam; the
Files panel should show visitors.txt changed.
Your name: Selam
Hana
Abel
SelamYour code
name = input("Your name: ")
# Add the name to visitors.txt, then print every lineIn the editor, press Escape then Tab to move on.
One answer per line, given to input() in order.
ፋይሎች1 starting file
visitors.txt
Hana Abel
መፍትሄውን አሳይHide the solution
This is one way to solve it, not the only one. If yours prints the same thing, it works.
name = input("Your name: ")
with open("visitors.txt", "a", encoding="utf-8") as f:
f.write(name + "\n")
with open("visitors.txt", encoding="utf-8") as f:
for line in f:
print(line.strip())ዋና ዋና ነጥቦች
with open(name, mode, encoding="utf-8") as f:opens a file and closes it when the block ends, even after an error."r"reads (the default),"w"empties the file and writes,"a"adds to the end.write()adds no\nof its own; lines you read keep theirs, sostrip()them.- An open file has a position: a second
read()returns"". - Catch
FileNotFoundErrorto start with nothing the first time a program runs.