Text files · ไฟล์ข้อความ (Text files)
Why files?
- Variables vanish when a program ends. A file keeps data on disk.
- Files let you save results and read them back later.
- They also hold more data than you would type by hand.
Open, use, close
open(name, mode)opens a file. The mode says what you will do."r"reads,"w"writes a fresh file (replacing any old text),"a"adds to the end.- Every file you open must be closed when you finish.
The with block
with open(...) as f:opens the file and closes it for you.- All the work goes in the indented block.
- This is the safest way — the file is never left open.
with open("greeting.txt", "w") as f:
f.write("Hi there\n")
with open("greeting.txt", "r") as f:
print(f.read())
Reading the lines
f.read()returns the whole file as one string.for line in f:reads it one line at a time.- Each line keeps its newline, so use
line.strip()to remove it.
with open("fruit.txt", "w") as f:
f.write("apple\npear\n")
with open("fruit.txt", "r") as f:
for line in f:
print(line.strip())
In Cambridge pseudocode
- The exam uses
OPENFILE,WRITEFILE,READFILE, andCLOSEFILE.
OPENFILE "notes.txt" FOR WRITE
WRITEFILE "notes.txt", "Hello"
CLOSEFILE "notes.txt"
OPENFILE "notes.txt" FOR READ
READFILE "notes.txt", line
CLOSEFILE "notes.txt"
OUTPUT line
Common mistakes
- Use
with open(...) as f:so the file closes itself. "w"erases the file first;"a"adds to the end.
Now you try
- This playground keeps files between runs, so write the file first, then read it in the same task.
- Press Check answer to test your code.
Reading a file · การอ่านไฟล์ (Reading a file)
A file is used in three steps: open, read, close. · การใช้ไฟล์ประกอบด้วยสามขั้นตอน: เปิด, อ่าน, ปิด (open, read, close)
In one run: write the two lines Hello and World to a file called notes.txt, then open it again, read it, and print what you read. · ในการรันหนึ่งครั้ง: เขียนสองบรรทัด Hello และ World ลงในไฟล์ชื่อ notes.txt จากนั้นเปิดมันอีกครั้ง อ่านมัน และ print สิ่งที่อ่านได้
Click Run to see the output here. · คลิก Run เพื่อดูผลลัพธ์ที่นี่
Write three lines to a file, then read it back and count the lines with a loop. Store the count in count (the answer is 3). · เขียนสามบรรทัดลงในไฟล์ แล้วอ่านกลับและนับจำนวนบรรทัดด้วยลูป เก็บจำนวนนับไว้ใน count (คำตอบคือ 3)
Click Run to see the output here. · คลิก Run เพื่อดูผลลัพธ์ที่นี่
Write the numbers 10, 20, 30 to a file, one per line. Then read them back, convert each line with int(...), and add them up in total (the answer is 60). · เขียนตัวเลข 10, 20, 30 ลงในไฟล์ โดยแต่ละตัวอยู่ในบรรทัดใหม่ จากนั้นอ่านกลับออกมา แปลงแต่ละบรรทัดด้วย int(...) และบวก它们在 total (คำตอบคือ 60)
Click Run to see the output here. · คลิก Run เพื่อดูผลลัพธ์ที่นี่