处理随机访问文件的程序很少将单个字段写入文件,往往采取每次写一个记录(或对象)的方式。可用其他语言定义一个类,用它表示要写入文件的记录,从而创建随机访问文件。在这种程序语言中,程序要根据类的长度在文件中读写类的实例(类的长度是指类的一个实例所占用的字节数)。Python提供了shelve模块模拟这种行为,利用它,程序员就不必另外写入一个新类。shelve模块在文件这读写记录。为此,要创建shelve对象来表示记录。这些对象具有一个字典接口——也就是访问记录信息的记录键。
2. 从shelve文件读取数据
1.将数据写入shelve文件
# Writing to shelve file.
import sys
import shelve
# open shelve file
try:
outCredit = shelve.open("credit.dat")
except IOError:
print >> sys.stderr, "open file failed"
sys.exit(1)
print "Enter account number(1 to 100, 0 to end)"
# get account information
while 1:
# get account information
accountNum = int(raw_input("\nEnter account number\n"))
if accountNum >0 and accountNum <= 100:
print "Enter last name, firstname, balance:"
currentData = raw_input("* ")
outCredit[str(accountNum)] = currentData.split()
elif accountNum == 0:
break
outCredit.close() # close shelve file
2. 从shelve文件读取数据
# read shelve file
import sys
import shelve
# print formated credit data
def print_account(account_num, account_list):
print account_num.ljust(10),
print account_list[0].ljust(10),
print account_list[1].ljust(10),
print account_list[2].rjust(10)
# open shelve file
try:
creditFile = shelve.open("credit.dat")
except IOError:
print >> sys.stderr, "open file failed"
sys.exit(1)
print "Account_Num".ljust(10),
print "FirstName", ljust(10),
print "LastName", ljust(10),
print "Balance".rjust(10)
# display each account info
for account_num in creditFile.keys():
print_account(account_num, creditFile[account_num])
creditFile.close()