python文件读写实例学习笔记

文件处理学习


shelve,cPickle模块

close()  关闭文件对象
flush()  刷新文件的缓冲区。缓冲区包含等待写入或文件中读取的信息。“刷新“就是执行实际的读取或写入操作
isatty()  如果文件对象是tty(终端)设备,就返回1
read([size]) 从文件中读取数据。
readline([size])  从文件中读取一行
readlines([size]) 从文件中读取多行
seek(offset[,location]) 使文件位置移动offset个字节。如果没有指定location,文件位置从文件起始处移动。如是指定了location,就从指定位置移动。
tell()  返回文件的当前位置
truncate([size])   删除文件中的数据。如果没有指定size,就删除所有数据;如果指定了size,就最多只删除指定的字节数。
write(output)   将字符串output写入文件
writeline(outputlist)   将outputlist中的每个字符串写入文件
writelines()   写入多行数据




一.创建顺序访问文件
写入文件
import sys
try:
    file=open("client.dat","w")
except IOError,message:
    print >> sys.stderr, "File could not be opened",message
    sys.exit(1)
print "Enter the accout,name and age."
while 1:
    try:
        accountline=raw_input("?")
    except EOFError:
        break
    else:
        print >>file,accountline
file.close()


读取数据
import sys
try:
    file=open("client.dat","r")
except IOError:
    print >> sys.stderr, "File could not be opened"
    sys.exit(1)
records=file.readlines()
print "Account",ljust(10)
print "Name",ljust(10)
print "age",ljust(10)
for record in records:
    fields=record.split()
    print fields[0].ljust(10),
    print fields[1].ljust(10),
    print fields[2].ljust(10),
file.close()

shelve模块应用
模拟随机访问文件:
import sys
import shelve
try:
    coutcredit=shelve.open("credit.dat")
except IOError:
    print >> sys.stderr,"File could not be opened"
    sys.exit(1)
print "Enter account number (1 to 100,0 to end input)"
while 1:
    accountNumber=int(raw_input("/nEnter account number/n?"))
    if 0 < accountNumber <= 100:
        print "Enter lastname, Firetname,balance"
        currentData=raw_input("?")
        outCredit[str{accountNumber)]=currentDdata.split()
    elif accountNumber==0:
        break
outCredit.close()

    
cPickle模块应用
注:cPickle模块的执行效率高于pickle
写文件
import sys
import cPickle
try:
    coutcredit=open("credit.dat","w")
except IOError:
    print >> sys.stderr,"File could not be opened"
    sys.exit(1)
print "Enter account number (1 to 100,0 to end input)"
inputlist=[]
while 1:
    try:
        accountline=raw_input("?")
    except EOFErrot:
        break
    else:
        inputlist.append(accountline.split())
cPickle.dump(inputlist,outCredit)
outCredit.close()

读出数据
import sys
import cPickle
try:
    outcredit=open("credit.dat","r")
except IOError:
    print >> sys.stderr,"File could not be opened"
    sys.exit(1)
records=cPickle.load(outcredit)
outcredit.close()
for record in records:
    print record[0].ljust(15),
    print record[1].ljust(10),
    print record[2].ljust(20)
 

文章出自:http://blog.chinaunix.net/u/12390/showart.php?id=154243

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值