您的位置:首页 > 编程语言 > Python开发

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

2015-04-02 22:32 525 查看
下面几个文件的命令比较常用:

close -- 关闭文件,相当于编辑器中的File->Save
read -- 读取文件内容分配给一个变量
readline -- 读取一行内容
truncate -- 清空文件,小心使用这个命令
write(stuff) -- 写入文件。
这些是你应该知道的重要命令,只有write需要提供参数。

让我们使用这些命令实现一个简单的文本编辑器。

[python] view
plaincopy

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, hot 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()  

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

运行结果

你会看到两个东西,一个是程序的输出:

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. 上面的代码有很
9e4f
多重复,想办法只使用一个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))
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: