python进行文件读写实例_python进行文件读写的实例

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()   写入多行数据

一、创建顺序访问文件

1)、写入文件 代码如下: 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

e

lse:

print >>file,accountline

file.close()

2)、读取数据 代码如下: 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()

3)、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()

4)、cPickle模块应用

注:cPickle模块的执行效率高于pickle

(1)、写入文件 代码如下: 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()

(2)、读取数据 代码如下: 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)

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值