Text files · 文本文件
Files keep data
- Variables vanish when a program ends; a file stores data so it lasts.
- The exam covers reading from and writing to text files.
- Work in three steps: open, read or write, then close.
文件保存数据
- 程序结束时变量就消失了;文件(file)把数据存下来,使它长期保留。
- 考试涉及对文本文件的读取和写入。
- 分三步进行:打开、读或写、再关闭。
Writing to a file
open(name, "w")opens a file for writing ("w"overwrites what was there).withcloses the file automatically when the block ends.\nstarts a new line in the file.
写入文件
open(name, "w")以写入方式打开文件("w"会覆盖原有内容)。with在代码块结束时自动关闭文件。\n在文件里另起一行。
with open("notes.txt", "w") as f:
f.write("Hello\n")
f.write("World\n")
Reading a file
open(name, "r")opens a file for reading..read()pulls in the whole contents as one string.
读取文件
open(name, "r")以读取方式打开文件。.read()把全部内容作为一个字符串读进来。
with open("notes.txt", "r") as f:
text = f.read()
print(text)
Reading line by line
- Looping over the file gives one line at a time — handy for totalling or counting.
逐行读取
- 遍历文件每次给出一行 —— 很适合用来累加或计数。
with open("notes.txt", "r") as f:
for line in f:
print(line.strip())
In the exam: file handling
- Pseudocode opens a file for a mode, reads or writes, then closes it.
在考试里:文件处理
- 伪代码以某种模式打开文件,读或写,然后关闭。
OPENFILE "notes.txt" FOR WRITE
WRITEFILE "notes.txt", "Hello"
CLOSEFILE "notes.txt"
Common mistakes
- Open, then read or write, then close the file.
- A line you read still carries its newline character.
常见错误
- 先打开,再读或写,最后关闭文件。
- 读到的一行仍带着换行符。
Now you try
- Write a file, then open it again to read it back.
- Press Check answer to test your code.
现在轮到你
- 写一个文件,然后重新打开把它读回来。
- 按检查答案来测试你的代码。
Using a file · 使用文件
A file is used in three steps: open, read or write, close. · 使用文件分三步:打开、读或写、关闭。
In one run: write the line Cambridge to a file called school.txt, then open it again, read it, and print what you read. · 在一次运行里:把 Cambridge 一行写入名为 school.txt 的文件,然后重新打开它、读取它,并 print 出读到的内容。
Click Run to see the output here. · 点击“运行”查看此处输出。
The starter writes three lines to a file. 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. · 点击“运行”查看此处输出。
The starter writes 10, 20, 30 to a file, one per line. 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. · 点击“运行”查看此处输出。