习题 16: 读写文件
阅读原文
如果你做了上一个练习的加分习题,你应该已经了解了各种文件相关的命令(方法/函数)。
你应该记住的命令如下:
- close -- 关闭文件。跟你编辑器的
文件->保存..一个意思。 - read -- 读取文件内容。你可以把结果赋给一个变量。
- readline -- 读取文本文件中的一行。
- truncate -- 清空文件,请小心使用该命令。
- write(stuff) -- 将stuff写入文件。
这是你现在该知道的重要命令。有些命令需要接受参数,这对我们并不重要。你
只要记住 write 的用法就可以了。 write 需要接收一个字符串作为参数,从而将该字符串写入文件。
让我们来使用这些命令做一个简单的文本编辑器吧:
from sys import argv
script, filename = argv
print "We're going to erase %r." % filename
print "If you don't want that, hit CTRL-C (^C)."
print "If you do want that, hit RETURN."
raw_input("?")
print "Opening the file..."
target = open(filename, 'w')
print "Truncating the file. Goodbye!"
target.truncate()
print "Now I'm going to ask you for three lines."
line1 = raw_input("line 1: ")
line2 = raw_input("line 2: ")
line3 = raw_input("line 3: ")
print "I'm going to write these to the file."
target.write(line1)
target.write("\n")
target.write(line2)
target.write("\n")
target.write(line3)
target.write("\n")
print "And finally, we close it."
target.close()
这个文件是够大的,大概是你键入过的最大的文件。所以慢慢来,仔细检查,让它能 运行起来。有一个小技巧就是你可以让你的脚本一部分一部分地运行起来。先写 1-8 行, 让它运行起来,再多运行 5 行,再接着多运行几行,以此类推,直到整个脚本运行起来为止。
What You Should See
你将看到两样东西,一样是你新脚本的输出:
$ python ex16.py test.txt
We're going to erase 'test.txt'.
If you don't want that, hit CTRL-C (^C).
If you do want that, hit RETURN.
?
Opening the file...
Truncating the file. Goodbye!
Now I'm going to ask you for three lines.
line 1: Mary had a little lamb
line 2: Its fleece was white as snow
line 3: It was also tasty
I'm going to write these to the file.
And finally, we close it.
接下来打开你新建的文件(我的是 test.txt )检查一下里边的内容,怎么样,不错吧?
Study Drills
- 如果你觉得自己没有弄懂的话,用我们的老办法,在每一行之前加上注解,为自己理清思路。\ 就算不能理清思路,你也可以知道自己究竟具体哪里没弄明白。
- 写一个和上一个练习类似的脚本,使用
read和argv读取你刚才新建的文件。 - 文件中重复的地方太多了。试着用一个
target.write()将line1,line2,line3打印出来,你可以使用字符串、格式化字符、以及转义字符。 - 找出为什么我们需要给
open多赋予一个'w'参数。提示:open对于文件的写入操作态度是安全第一,所以你只有特别指定以后,它才会进行写入操作。
Common Student Questions
Is the truncate() necessary with the 'w' parameter? |
|---|
| See Study Drills 5. |
What does 'w' mean? |
It's really just a string with a character in it for the kind of mode for the file. If you use 'w' then you're saying "open this file in 'write' mode," thus the 'w' character. There's also 'r' for "read," 'a' for append, and modifiers on these. |
| What modifiers to the file modes can I use? |
The most important one to know for now is the + modifier, so you can do 'w+', 'r+', and 'a+'. This will open the file in both read and write mode, and depending on the character use position the file in different ways. |
Does just doing open(filename) open it in 'r' (read) mode? |
Yes, that's the default for the open() function. |
Copyright (C) 2010 by
Author: Zed Shaw
Translator:Zander Wong