p16 读写文件

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

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

 16.py

 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("\n")
27 target.write(line2)
28 target.write("\n")
29 target.write(line3)
30 target.write("\n")
31 
32 print "And finally, we close it."
33 target.close()

写一个和上一个练习类似的脚本,使用 readargv 读取你刚才新建的文件。

1 from sys import argv
2 
3 script, filename = argv 
4 print "%r have opened" % filename
5 
6 open_file = open(filename)
7 print open_file.read()

  • 文件中重复的地方太多了。试着用一个 target.write()line1, line2, line3打印出来,你可以使用字符串、格式化字符、以及转义字符。
  • 找出为什么我们需要给 open 多赋予一个 'w' 参数。提示: open 对于文件的写入操作态度是安全第一,所以你只有特别指定以后,它才会进行写入操作
原文地址:https://www.cnblogs.com/linuxroot/p/2753330.html