Learn Python The Hard Way学习(16) - 读写文件

来源:互联网 发布:自学凸优化 编辑:程序博客网 时间:2024/06/06 02:31
下面几个文件的命令比较常用:
  • close -- 关闭文件,相当于编辑器中的File->Save
  • read -- 读取文件内容分配给一个变量
  • readline -- 读取一行内容
  • truncate -- 清空文件,小心使用这个命令
  • write(stuff) -- 写入文件。
这些是你应该知道的重要命令,只有write需要提供参数。

让我们使用这些命令实现一个简单的文本编辑器。
[python] view plaincopy
  1. from sys import argv  
  2.   
  3.   
  4. script, filename = argv  
  5.   
  6.   
  7. print "We're going to erase %r." % filename  
  8. print "If you don't want that, hit CTRL-C (^C)."  
  9. print "If you do want that, hot RETURN."  
  10.   
  11.   
  12. raw_input("?")  
  13.   
  14.   
  15. print "Opening the file..."  
  16. target = open(filename, 'w')  
  17.   
  18.   
  19. print "Truncating the file. Goodbye!!"  
  20. target.truncate()  
  21.   
  22.   
  23. print "Now I'm going to ask you for three lines."  
  24.   
  25.   
  26. line1 = raw_input("line 1: ")  
  27. line2 = raw_input("line 2: ")  
  28. line3 = raw_input("line 3: ")  
  29.   
  30.   
  31. print "I'm going to write these to the file."  
  32.   
  33.   
  34. target.write(line1)  
  35. target.write("\n")  
  36. target.write(line2)  
  37. target.write("\n")  
  38. target.write(line3)  
  39. target.write("\n")  
  40.   
  41.   
  42. print "And finally, we close it."  
  43. target.close()  

这个程序比较长,所以慢慢来,让它能运行起来。有个办法是,先写几行,运行一下,可以运行再写几行,直到都可以运行。

运行结果
你会看到两个东西,一个是程序的输出:
root@he-desktop:~/mystuff# 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, hot RETURN.
?
Opening the file...
Truncating the file. Goodbye!!
Now I'm going to ask you for three lines.
line 1: Hi!
line 2: Welcome to my blog!
line 3: Thank you!
I'm going to write these to the file.
And finally, we close it.

还有就是你新建立的文件,打开看看吧。

加分练习
1. 如果你不明白上面的程序的话,回去给每行加上注释吧,注释能让你理清思路,更好的理解程序。

2. 写一个像上一节那样的程序,使用read和argv去读取我们刚刚建立的文件。

3. 上面的代码有很多重复,想办法只使用一个target.write()代替上面的6行。
lines = "%s\n%s\n%s\n" % (line1, line2, line3)
target.write(lines)

4. 为什么open的时候要使用一个额外的参数'w'呢?提示:如果不用写入文件,open操作是安全的。

5. 如果使用'w'方式,必须使用target.truncate()方法吗?去读一下open方法的文档。

不用,不管是w方式还是w+方式,都会清除文件内容。



---chenlin:同时写入几行内容的几种方法:

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")

#lines = "%s\n%s\n%s\n" % (line1, line2, line3)
#target.write(lines)

#target.write(line1 + "\n" + line2 + "\n" +  line3 + "\n")

target.write("%s\n%s\n%s\n" %(line1, line2, line3))

0 0
原创粉丝点击