如果你做了上一个练习的加分习题,你应该已经了解了各种文件相关的命令(方法/函数)。你应该记住的命令如下:
这是你现在该知道的重要命令。有些命令需要接受参数,这对我们并不重要。你只要记住 write 的用法就可以了。 write 需要接收一个字符串作为参数,从而将该字符串写入文件。
让我们来使用这些命令做一个简单的文本编辑器吧:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | 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 行,再接着多运行几行,以此类推,直到整个脚本运行起来为止。
你将看到两样东西,一样是你新脚本的输出:
$ 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: To all the people out there.
line 2: I say I don't like my hair.
line 3: I need to shave it off.
I'm going to write these to the file.
And finally, we close it.
$
接下来打开你新建的文件(我的是 test.txt )检查一下里边的内容,怎么样,不错吧?