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.
为什么需要文件?
- 程序结束时变量就消失了。文件(file)把数据保存在磁盘上。
- 文件让你保存结果,以后再读回来。
- 文件也能存放比你手动输入多得多的数据。
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.
打开、使用、关闭
open(name, mode)打开一个文件。模式(mode)说明你要做什么。"r"读取,"w"写入一个全新文件(替换旧内容),"a"追加到末尾。- 每个打开的文件,用完都必须关闭。
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 代码块
with open(...) as f:会打开文件,并替你关闭它。- 所有操作都写在缩进的代码块里。
- 这是最安全的方式 —— 文件绝不会被忘记关闭。
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.
逐行读取
f.read()把整个文件作为一个字符串返回。for line in f:会一行一行地读取。- 每行都带着换行符,所以用
line.strip()把它去掉。
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、WRITEFILE、READFILE和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.
常见错误
- 用
with open(...) as f:,文件会自动关闭。 "w"会先清空文件;"a"追加到末尾。
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 · 读取文件
A file is used in three steps: 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. · 点击“运行”查看此处输出。
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. · 点击“运行”查看此处输出。
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. · 点击“运行”查看此处输出。