2

我正在尝试从文件中获取腌制列表,但我不断收到错误。是否需要在每个函数中从同一个文件中解压相同的对象,或者解压一次就可以了?

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

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)
4

1 回答 1

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]
于 2013-07-19T00:27:31.267 回答