Text files
Python for IGCSE CS Lesson 12 2:09 English narration · English + 中文 subtitles burned in
Chapters
Transcript
Variables vanish when a program ends; a file does not.
程序一结束,变量就消失了;文件不会。
Working with one always takes three steps, and the exam expects all three.
使用文件永远是三步,而考试要求这三步都在。
Open the file, naming it and saying whether you want to read or write.
打开文件,给出名字,并说明你要读还是要写。
Then the actual work.
然后是真正的操作。
Then close it, so the data is safely saved.
然后关闭它,让数据被安全地保存。
Python's with block does that third step for you automatically — which is convenient, but the exam writes CLOSEFILE, so know that it is happening.
Python 的 with 块会自动替你做第三步—— 这很方便,但考卷上写的是 CLOSEFILE, 所以你要知道这一步确实在发生。
Open with the write mode and call write, and the file now holds what you put there.
用写模式打开,调用 write,文件里装的就是你写进去的内容。
Two things print quietly did for you that write does not.
有两件事 print 悄悄替你做了,而 write 不会。
First, the write mode empties the file before you start — anything that was in it is gone.
第一,写模式会在你开始之前把文件清空——原来的内容全没了。
Second, there is no automatic new line, so you have to add the newline yourself at the end of each one.
第二,它不会自动换行, 所以每一行结尾的换行符要你自己加上。
There are two ways to read.
读取有两种方式。
Read with no arguments pulls the whole file in as one long string, which is fine when you just want to show it.
不带参数的 read 把整个文件作为一个长字符串读进来, 只是想显示出来的话,这就够了。
Or loop over the file itself, and you get one line at a time — which is what you want for counting or totalling.
或者直接对文件本身做循环,你会一次得到一行—— 要计数或求和时,你想要的就是这个。
One catch: a line you read still carries its newline on the end, so strip it before converting with int.
有一个坑: 你读到的每一行末尾还带着换行符, 所以用 int 转换之前要先把它去掉。
The first task is the whole round trip in one program: write a line, then open the file again and read it back.
第一道题是在一个程序里完成整个来回: 写入一行,然后再次打开文件,把它读回来。
Notice there are two opens, not one.
注意这里是两次打开,不是一次。
The mode is fixed when you open, so you cannot write and then read through the same handle.
模式在打开的那一刻就定下了, 所以你不能用同一个句柄先写再读。
On the exam side, each open has its own matching close.
在考卷那一边,每一次打开都有与之配对的关闭。
Four things to take with you.
带走四点。
One: a file keeps data after the program ends.
第一:文件在程序结束之后仍然保存着数据。
Two: open, then read or write, then close.
第二:先打开,再读或写,然后关闭。
Three: looping the file gives one line at a time.
第三:对文件做循环,一次得到一行。
Four: the write mode empties the file first, so never open for writing when you meant to add.
第四:写模式会先把文件清空, 所以当你其实是想追加时,千万别用写模式打开。
Now do the three tasks.
现在去做那三道题。