模拟随机访问文件:shelve模块

处理随机访问文件的程序很少将单个字段写入文件,往往采取每次写一个记录(或对象)的方式。可用其他语言定义一个类,用它表示要写入文件的记录,从而创建随机访问文件。在这种程序语言中,程序要根据类的长度在文件中读写类的实例(类的长度是指类的一个实例所占用的字节数)。Python提供了shelve模块模拟这种行为,利用它,程序员就不必另外写入一个新类。shelve模块在文件这读写记录。为此,要创建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()



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值