怎么阅读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)
温馨提示:答案为网友推荐,仅供参考