Text files · Tệp văn bản
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.
Tại sao cần tệp?
- Biến mất đi khi chương trình kết thúc. Một tệp giữ dữ liệu trên đĩa.
- Tệp cho phép bạn lưu kết quả và đọc lại chúng sau này.
- Chúng cũng chứa nhiều dữ liệu hơn những gì bạn có thể gõ bằng tay.
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.
Mở, sử dụng, đóng
open(name, mode)mở một tệp. Mode (chế độ) cho biết bạn sẽ làm gì với nó."r"đọc,"w"ghi vào một tệp mới (thay thế văn bản cũ),"a"thêm vào cuối.- Mọi tệp bạn mở đều phải được đóng khi bạn hoàn thành.
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.
Khối with
with open(...) as f:mở tệp và đóng nó cho bạn.- Tất cả công việc diễn ra trong khối thụt vào.
- Đây là cách an toàn nhất — tệp không bao giờ bị bỏ mở.
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.
Đọc từng dòng
f.read()trả về toàn bộ tệp như một chuỗi duy nhất.for line in f:đọc nó một dòng một.- Mỗi dòng giữ ký tự xuống dòng của nó, nên hãy dùng
line.strip()để loại bỏ nó.
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.
Trong pseudocode Cambridge
- Đề thi sử dụng
OPENFILE,WRITEFILE,READFILE, vàCLOSEFILE.
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.
Lỗi thường gặp
- Dùng
with open(...) as f:để tệp tự động đóng lại. "w"xóa tệp trước;"a"thêm vào cuối.
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.
Bây giờ bạn thử
- Sân chơi này giữ các tệp giữa các lần chạy, vì vậy hãy ghi tệp trước, sau đó đọc nó trong cùng một bài tập.
- Nhấn Check answer (Kiểm tra câu trả lời) để thử mã của bạn.
Reading a file · Đọc tệp
A file is used in three steps: open, read, close. · Một tệp được sử dụng qua ba bước: mở, đọc, đóng.
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. · Trong một lần chạy: viết hai dòng Hello và World vào tệp có tên notes.txt, sau đó mở lại nó, đọc nội dung và print những gì bạn vừa đọc.
Click Run to see the output here. · Nhấn Chạy để xem kết quả ở đây.
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). · Viết ba dòng vào tệp, sau đó đọc lại và đếm số dòng bằng vòng lặp. Lưu kết quả đếm vào count (kết quả là 3).
Click Run to see the output here. · Nhấn Chạy để xem kết quả ở đây.
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). · Viết các số 10, 20, 30 vào tệp, mỗi số trên một dòng. Sau đó đọc lại chúng, chuyển đổi mỗi dòng bằng int(...), và tính tổng trong total (kết quả là 60).
Click Run to see the output here. · Nhấn Chạy để xem kết quả ở đây.