笨办法学Python(十六)

习题 16: 读写文件

如果你做了上一个练习的加分习题,你应该已经了解了各种文件相关的命令(方法/函数)。你应该记住的命令如下:

  • close – 关闭文件。跟你编辑器的 文件->保存.. 一个意思。
  • read – 读取文件内容。你可以把结果赋给一个变量。
  • readline – 读取文本文件中的一行。
  • truncate – 清空文件,请小心使用该命令。
  • write(stuff) – 将stuff写入文件。

这是你现在该知道的重要命令。有些命令需要接受参数,这对我们并不重要。你只要记住 write 的用法就可以了。 write 需要接收一个字符串作为参数,从而将该字符串写入文件。

让我们来使用这些命令做一个简单的文本编辑器吧:

 1 from sys import argv
 2 
 3 script, filename = argv
 4 
 5 print "We're going to erase %r." % filename
 6 print "If you don't want that, hit CTRL-C (^C)."
 7 print "If you do want that, hit RETURN."
 8 
 9 raw_input("?")
10 
11 print "Opening the file..."
12 target = open(filename, 'w')
13 
14 print "Truncating the file.  Goodbye!"
15 target.truncate()
16 
17 print "Now I'm going to ask you for three lines."
18 
19 line1 = raw_input("line 1: ")
20 line2 = raw_input("line 2: ")
21 line3 = raw_input("line 3: ")
22 
23 print "I'm going to write these to the file."
24 
25 target.write(line1)
26 target.write("
")
27 target.write(line2)
28 target.write("
")
29 target.write(line3)
30 target.write("
")
31 
32 print "And finally, we close it."
33 target.close()
View Code

这个文件是够大的,大概是你键入过的最大的文件。所以慢慢来,仔细检查,让它能运行起来。有一个小技巧就是你可以让你的脚本一部分一部分地运行起来。先写 1-8 行,让它运行起来,再多运行 5 行,再接着多运行几行,以此类推,直到整个脚本运行起来为止。

你应该看到的结果

你将看到两样东西,一样是你新脚本的输出:

    

接下来打开你新建的文件(我的是 test.txt )检查一下里边的内容,怎么样,不错吧?

    

加分习题

  1. 如果你觉得自己没有弄懂的话,用我们的老办法,在每一行之前加上注解,为自己理清思路。就算不能理清思路,你也可以知道自己究竟具体哪里没弄明白。
  2. 写一个和上一个练习类似的脚本,使用 read 和 argv 读取你刚才新建的文件。
  3. 文件中重复的地方太多了。试着用一个 target.write() 将 line1line2line3 打印出来,你可以使用字符串、格式化字符、以及转义字符。
  4. 找出为什么我们需要给 open 多赋予一个 'w' 参数。提示: open 对于文件的写入操作态度是安全第一,所以你只有特别指定以后,它才会进行写入操作。

习题练习

1.

原文地址:https://www.cnblogs.com/yllinux/p/7355355.html