酸洗如何在不同范围内起作用?

时间:2013-07-18 23:34:23

标签: python pickle

我正在尝试从文件中获取一个腌制列表,但我只是不断收到错误。是否需要在每个函数中对同一个文件中的同一个对象进行unpickling,或者可以将它解开一次吗?

这是我尝试过的最后一件事:

import pickle, sys

def openFile(fileName, mode):
    """Open a file."""

    try:
        file =  open(fileName, mode)
    except IOError as e:
        print("Unable to open the file", fileName)
        print(e)
        input("Press the enter key to exit.")
        sys.exit()
    else:
        return file

def writeScore(file, score):
    """Write score to file."""

    try:
        highScores = pickle.load(file)
    except IOError as e:
        print("File doesn't exist.")
        print(e)
    except EOFError as e:
        print("File is empty.")
        print(e)
    else:
        highScores.append(score)
        highScores = highScores.sort()
        pickle.dump(highScores, file)

score_file = openFile("highScores.dat", "ab+")
writeScore(score_file, 1000)
score_file.close()

score_file = openFile("highScores.dat", "rb")
highScore = pickle.load(score_file)
print(highScore)

1 个答案:

答案 0 :(得分:1)

您想要在打开的文件中使用pickle.load()进行追加,而不是阅读。此外,您的函数openFile()open()基本相同。

我的建议:

import pickle

def writeScore(file_, score):
    """Write score to file."""

    try:
        cache_file = open(file_, 'rb')
    except IOError:
        open(file_, 'a').close()
        cache_file = open(file_, 'rb')

    try:
        highScores = pickle.load(cache_file)
        highScores.append(score)
        highScores.sort()
    except EOFError:
        highScores = [score]
    finally:
        cache_file.close()

    writing_file = open(file_, 'wb')
    pickle.dump(highScores, writing_file)
    writing_file.close()

def displayScores(file_):
    """Display score from file."""

    cache_file = open(file_, 'rb')
    try:
        print pickle.load(cache_file)
    except (EOFError, IOError):
        print 'No scores to display.'

if __name__ == '__main__':
    scores_file = 'highScores.dat'

    writeScore(scores_file, 2000)
    displayScores(scores_file)

    writeScore(scores_file, 1000)
    displayScores(scores_file)

或者,更好的是,使用shelve。你甚至不需要这些功能:

import shelve

def startDatabase(file_):
    """Creates a shelve from file."""

    return shelve.open(file_, writeback=True)

def writeScore(database, score):
    """Write score to file."""

    try:
        database['scores'].append(score)
        database['scores'].sort()
    except KeyError:
        database['scores'] = [score]

def displayScores(database):

    try:
        print database['scores']
    except KeyError:
        print 'No scores to display.'

if __name__ == '__main__':
    db = startDatabase('highScores.dat')

    displayScores(db)

    writeScore(db, 2000)
    displayScores(db)

    writeScore(db, 1000)
    displayScores(db)

    db.close()

两者产生相同的输出:

No scores to display.
[1000]
[1000, 2000]