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

python16 文件的读写

2013-08-30 09:26 351 查看
开始本章之前,先记住下面一些方法

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'表示不同的意思。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: