通知短信+运营短信,5秒速达,支持群发助手一键发送🚀高效触达和通知客户 广告
# 习题 16: 读写文件 如果你做了上一个练习的加分习题,你应该已经了解了各种文件相关的命令(方法/函数)。你应该记住的命令如下: - close – 关闭文件。跟你编辑器的 文件->保存.. 一个意思。 - read – 读取文件内容。你可以把结果赋给一个变量。 - readline – 读取文本文件中的一行。 - truncate – 清空文件,请小心使用该命令。 - write(stuff) – 将stuff写入文件。 这是你现在该知道的重要命令。有些命令需要接受参数,这对我们并不重要。你只要记住 write 的用法就可以了。 write 需要接收一个字符串作为参数,从而将该字符串写入文件。 让我们来使用这些命令做一个简单的文本编辑器吧: <table class="highlighttable"><tbody><tr><td class="linenos"> <div class="linenodiv"> <pre> 1&#13; 2&#13; 3&#13; 4&#13; 5&#13; 6&#13; 7&#13; 8&#13; 9&#13; 10&#13; 11&#13; 12&#13; 13&#13; 14&#13; 15&#13; 16&#13; 17&#13; 18&#13; 19&#13; 20&#13; 21&#13; 22&#13; 23&#13; 24&#13; 25&#13; 26&#13; 27&#13; 28&#13; 29&#13; 30&#13; 31&#13; 32&#13; 33</pre> </div> </td> <td class="code"> <div class="highlight"> <pre>from sys import argv&#13; &#13; script, filename = argv&#13; &#13; print "We're going to erase %r." % filename&#13; print "If you don't want that, hit CTRL-C (^C)."&#13; print "If you do want that, hit RETURN."&#13; &#13; raw_input("?")&#13; &#13; print "Opening the file..."&#13; target = open(filename, 'w')&#13; &#13; print "Truncating the file. Goodbye!"&#13; target.truncate()&#13; &#13; print "Now I'm going to ask you for three lines."&#13; &#13; line1 = raw_input("line 1: ")&#13; line2 = raw_input("line 2: ")&#13; line3 = raw_input("line 3: ")&#13; &#13; print "I'm going to write these to the file."&#13; &#13; target.write(line1)&#13; target.write("\n")&#13; target.write(line2)&#13; target.write("\n")&#13; target.write(line3)&#13; target.write("\n")&#13; &#13; print "And finally, we close it."&#13; target.close()&#13; </pre> </div> </td> </tr></tbody></table> 这个文件是够大的,大概是你键入过的最大的文件。所以慢慢来,仔细检查,让它能运行起来。有一个小技巧就是你可以让你的脚本一部分一部分地运行起来。先写 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 )检查一下里边的内容,怎么样,不错吧? ### 加分习题 1. 如果你觉得自己没有弄懂的话,用我们的老办法,在每一行之前加上注解,为自己理清思路。就算不能理清思路,你也可以知道自己究竟具体哪里没弄明白。 1. 写一个和上一个练习类似的脚本,使用 read 和 argv 读取你刚才新建的文件。 1. 文件中重复的地方太多了。试着用一个 target.write() 将 line1, line2, line3 打印出来,你可以使用字符串、格式化字符、以及转义字符。 1. 找出为什么我们需要给 open 多赋予一个 'w' 参数。提示: open 对于文件的写入操作态度是安全第一,所以你只有特别指定以后,它才会进行写入操作。