+ -
当前位置:首页 → 问答吧 → shelve文件的读写问题

shelve文件的读写问题

时间:2011-03-04

来源:互联网

本帖最后由 eeeee159963 于 2011-03-04 11:07 编辑
  1. # Fig. 14.9: fig14_09.py
  2. # Writing to shelve file.

  3. import sys
  4. import shelve

  5. # open shelve file
  6. try:
  7.    outCredit = shelve.open( "credit.dat" )
  8. except IOError:
  9.    print >> sys.stderr, "File could not be opened"
  10.    sys.exit( 1 )

  11. print "Enter account number (1 to 100, 0 to end input)"

  12. # get account information
  13. while 1:

  14.    # get account information
  15.    accountNumber = int( raw_input(
  16.          "\nEnter account number\n? " ) )
  17.       
  18.    if 0 < accountNumber <= 100:
  19.       
  20.       print "Enter lastname, firstname, balance"
  21.       currentData = raw_input( "? " )

  22.       outCredit[ str( accountNumber ) ] = currentData.split()

  23.    elif accountNumber == 0:
  24.       break

  25. outCredit.close()   # close shelve file
复制代码
第九行outCredit = shelve.open( "credit.dat" )是读取文件的意思(默认"r"模式),但这个程序的功能是写文件,
我以为第九行应该换成outCredit = shelve.open( "credit.dat" , "w"),不知道对不对呢

作者: eeeee159963   发布时间: 2011-03-04

本帖最后由 iamkey9 于 2011-03-04 15:35 编辑

默认是c  - 读写建


shelve.open(filename[, flag='c'[, protocol=None[, writeback=False]]])&para;

Open a persistent dictionary. The filename specified is the base filename for the underlying database. As a side-effect, an extension may be added to the filename and more than one file may be created. By default, the underlying database file is opened for reading and writing. The optional flag parameter has the same interpretation as the flag parameter of anydbm.open().



anydbm.open(filename[, flag[, mode]])&para;

Open the database file filename and return a corresponding object.

If the database file already exists, the whichdb module is used to determine its type and the appropriate module is used; if it does not exist, the first module listed above that can be imported is used.

The optional flag argument must be one of these values:

Value Meaning
'r' Open existing database for reading only (default)
'w' Open existing database for reading and writing
'c' Open database for reading and writing, creating it if it doesn’t exist
'n' Always create a new, empty database, open for reading and writing

作者: iamkey9   发布时间: 2011-03-04

热门下载

更多