A notes script saves one line, prints it back, and counts the lines in the file. It prints the note, then jumlah baris: 0. The file on disk contains the note, and the program exits with status 0, so nothing looks broken.
Key takeaways
read()moves the file pointer to the end, so a secondread()on the same handle returns''and every count built on it is zero.- The file on disk is fine:
tell()reports 5 after reading a 5-byte file, which is where the next read starts. - Read once into a variable and count that, or call
seek(0)to send the pointer back to the start. open(path, "a")appends and creates the file when it is missing, while"w"empties it before writing, so the mode determines whether yesterday's notes survive.
The count that says zero
Save this as notes.py. It appends the note you pass on the command line, then opens the file to show it and count the lines.
# notes.py
import sys
path = sys.argv[1]
note = sys.argv[2]
with open(path, "a") as handle:
handle.write(note + "\n")
handle = open(path)
print("catatan tersimpan:")
print(handle.read(), end="")
print("jumlah baris:", len(handle.read().splitlines()))
Run it once against a file that does not exist yet.
$ python3 notes.py notes.txt "beli kopi"
catatan tersimpan:
beli kopi
jumlah baris: 0
The note prints, but the count does not match it. cat notes.txt shows the line was written, so the write worked and the read is what came back wrong.
The file was fine; the pointer was not
open() gives you a handle with a position, and read() moves that position to the end of the file. After the first note, notes.txt holds ten bytes, so the pointer sits at byte 10. The next read() starts there, finds no bytes left, and returns an empty string instead of an error.
notes.py calls handle.read() twice on the same handle. The first call sits inside print(handle.read(), end="") and returns the note. The second sits inside len(handle.read().splitlines()) and starts at the end with nothing left to give. len("".splitlines()) is 0, and the script prints 0 with no error. No exception is raised, so the exit status stays 0.
The checker
check_notes.py runs notes.py three times against one file in a temporary folder, once per note, so the file should hold one line, then two, then three. After the first run it opens the file itself and compares the contents with beli kopi\n, so that check never depends on what the script prints. The other checks search the output for jumlah baris: 1, jumlah baris: 2 and jumlah baris: 3. When a count check fails, it prints the last line of that output after <-, so you see the number the script reported.
# check_notes.py
import os
import subprocess
import sys
import tempfile
HERE = os.path.dirname(os.path.abspath(__file__))
SUBJECT = os.path.join(HERE, "notes.py")
passed = 0
failed = 0
def check(label, condition, detail=""):
global passed, failed
if condition:
passed += 1
print(f"PASS {label}")
else:
failed += 1
print(f"FAIL {label}" + (f" <- {detail}" if detail else ""))
def run(path, note):
return subprocess.run(
[sys.executable, SUBJECT, path, note],
capture_output=True,
text=True,
)
def last_line(text):
lines = text.strip().splitlines()
return lines[-1] if lines else "(no output)"
with tempfile.TemporaryDirectory() as folder:
path = os.path.join(folder, "notes.txt")
first = run(path, "beli kopi")
check("the script exits without an error", first.returncode == 0, last_line(first.stderr))
with open(path) as handle:
isi = handle.read()
check("the first note reaches the file", isi == "beli kopi\n", repr(isi))
check("it prints the note it just saved", "beli kopi" in first.stdout)
check("it counts one line", "jumlah baris: 1" in first.stdout, last_line(first.stdout))
second = run(path, "telepon ibu")
check("the second run keeps the first note", "beli kopi" in second.stdout)
check("it counts two lines", "jumlah baris: 2" in second.stdout, last_line(second.stdout))
third = run(path, "bayar listrik")
check("it counts three lines", "jumlah baris: 3" in third.stdout, last_line(third.stdout))
print()
print(f"{passed} of {passed + failed} checks passed")
sys.exit(1 if failed else 0)
The starter fails three checks and passes four.
$ python3 check_notes.py
PASS the script exits without an error
PASS the first note reaches the file
PASS it prints the note it just saved
FAIL it counts one line <- jumlah baris: 0
PASS the second run keeps the first note
FAIL it counts two lines <- jumlah baris: 0
FAIL it counts three lines <- jumlah baris: 0
4 of 7 checks passed
The four passes cover the exit status, the file contents, and the note appearing on both runs. Exit status 0 only means Python did not crash; the three count checks still fail with <- jumlah baris: 0 because the count is the only output built on the second read().
Read once, then count
Read the file into a variable, then count the variable.
# notes.py
import sys
path = sys.argv[1]
note = sys.argv[2]
with open(path, "a") as handle:
handle.write(note + "\n")
with open(path) as handle:
isi = handle.read()
print("catatan tersimpan:")
print(isi, end="")
print("jumlah baris:", len(isi.splitlines()))
Two runs now agree with the file.
$ python3 notes.py notes.txt "beli kopi"
catatan tersimpan:
beli kopi
jumlah baris: 1
$ python3 notes.py notes.txt "telepon ibu"
catatan tersimpan:
beli kopi
telepon ibu
jumlah baris: 2
The checker is green. The count now comes from isi, the string you already read, so no second read() is left to come back empty.
$ python3 check_notes.py
PASS the script exits without an error
PASS the first note reaches the file
PASS it prints the note it just saved
PASS it counts one line
PASS the second run keeps the first note
PASS it counts two lines
PASS it counts three lines
7 of 7 checks passed
handle.seek(0) before the second read does the same job on one handle: it sends the pointer back to the start. Reading once is shorter, so start there.
Append is not overwrite
open(path, "a") adds at the end and creates the file when it is missing. open(path, "w") empties it first, then writes at the start.
Change the "a" in your copy to "w" and run the checker again. You get 4 of 7 checks passed. The second run no longer shows the first note, and the counts for two and three lines fail. The count reads 1 on every run, because the file only ever holds the line you just wrote. Nothing raised an error, and the earlier notes were overwritten.