开始本章之前,先记住下面一些方法
学习要点:
- close -- 关闭一个文件,同时对它进行保存。
- read -- 读取一个文件的内容,你可以把内容赋值给一个变量。
- readline -- 仅读取一行的内容。
- truncate -- 清空文件,这个要小心使用。
- write(stuff) -- 把stuff写到文件中。
看下代码ex16.py
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, hit 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()
学习要点:
1、CTRL-C 可以中止正在运行的python脚本
2、open方法添加了'w' 参数,表示以可写的方式打开一个文件,如果这个文件不存在,创建它
3、truncate把文件的内容全部清空了
4、write(stuff)把stuff写到文件中,注意以“\n”表示换行
5、close关闭并保
6、python -m pydoc file可以查看open更多的参数,'r','w','a'表示不同的意思。