Text files
Python for A-Level CS Lesson 2 2:02 English narration · English + 中文 subtitles burned in
Chapters
Transcript
Opening a file takes a mode, and the mode is not a formality.
打开文件要给一个模式,而这个模式不是走过场。
Read gives you what is there.
读模式给你文件里已有的内容。
Write throws away what was there and starts a fresh file.
写模式把原有内容丢掉,重新开始一个空文件。
Append adds to the end and keeps everything.
追加模式加在末尾,并保留全部内容。
Look at the middle one: two days of log, gone, because someone typed w where they meant a.
看中间那个:两天的日志没了, 只因为有人把 "a" 打成了 "w"。
It does not warn you and it cannot be undone.
它不会警告你,而且撤销不了。
You could open a file, work with it, and close it by hand.
你当然可以手动打开文件、使用它、再关闭它。
The trouble is what happens when a line in between fails — the close never runs.
问题在于中间某一行失败时会怎样——那个 close 就永远不会执行。
A with block closes it for you at the end of the block, whether the code succeeded or raised.
with 块会在块结束时替你关闭它, 不管代码是成功了还是抛出了异常。
And this matters more than tidiness: until a file is closed, what you wrote may not have reached the disk at all.
而这比"整洁"重要得多: 在文件被关闭之前,你写进去的内容可能根本还没到磁盘上。
Two ways to read.
读取有两种方式。
Read with no arguments gives you the whole file as one string.
不带参数的 read 把整个文件作为一个字符串给你。
Looping over the file gives you one line at a time, which is what you want for counting or totalling.
对文件做循环,则一次给你一行, 要计数或求和时,你要的就是这个。
And every line you get still carries the newline you wrote on the end of it — so if you are about to convert it to a number, strip it first.
而你拿到的每一行,末尾仍然带着你写进去的那个换行符—— 所以如果你接下来要把它转成数字,先把它去掉。
The third task writes three numbers and then totals them back.
第三道题先写三个数字,再把它们读回来求和。
Look at the str in the write line — a file holds text, nothing else, so a number has to be converted on the way in.
注意写入那一行里的 str—— 文件里装的只有文本,别的什么都没有, 所以数字进去之前必须先转换。
And on the way out it has to be converted back with int, after stripping the newline.
出来的时候也一样,去掉换行符之后要用 int 转回来。
Text going out, text coming in; the conversions are yours to do at both ends.
写出去是文本,读进来也是文本; 两头的转换都得你自己做。
Four things to take with you.
带走四点。
One: the mode says read, write or append.
第一:模式决定是读、是写,还是追加。
Two: the write mode replaces the file entirely.
第二:写模式会把整个文件替换掉。
Three: a with block closes the file whatever happens.
第三:with 块无论发生什么都会关闭文件。
Four: loop the file for a line at a time, then strip it before converting.
第四:对文件做循环一次拿一行,转换前先去掉换行符。
Now do the three tasks.
现在去做那三道题。