python16 文件的读写

开始本章之前,先记住下面一些方法
  • 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'表示不同的意思。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值