python学习(9)———文件操作

常用文件操作函数

  • open():打开文件
  • read():读取文件的内容,可以把内容赋值给一个变量。
  • close():关闭文件,就像文件编辑器里面的保存
  • readline():读取文件中的一行
  • truncate():清空文件中的内容
  • write(‘stuff’):向文件中写数据’stuff’
    代码:
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()

得到的结果图:
这里写图片描述
以及文件data.in中的数据:
这里写图片描述
我们可以看到在读取文件的时候在后面加了一个字符’w’。这个符号表示用怎么得方式读取文件。一共有三种方式读取文件(r,w,a):


  • r方式:就是只读方式,可以在后添加+,b等r+表示可读写,rb表示以二进制读取;
  • w方式:就是只写方式,可以在后添加+,b等w+表示可读写,wb表示以二进制读取;
  • a方式:就是从在文章末尾写的方式,可以在后田间+,b,意思同上。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值