Python3:EOFError: Ran out of input

solution發表於2021-09-09

使用pickle.load(f)載入pickle檔案時,報錯:EOFError: Ran out of input.
可能原因:檔案為空。
解決辦法:載入非空檔案。
其他解決辦法:
1、載入前判斷檔案是否為空

import os

scores = {} # scores is an empty dict already

if os.path.getsize(target) > 0:      

    with open(target, "rb") as f:

        unpickler = pickle.Unpickler(f)

        # if file is not empty scores will be equal

        # to the value unpickled

        scores = unpickler.load()


2、捕獲異常

open(target, 'a').close()

scores = {};

try:

    with open(target, "rb") as file:

        unpickler = pickle.Unpickler(file);

        scores = unpickler.load();

        if not isinstance(scores, dict):

            scores = {};

except EOFError:

    return {}


來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/2459/viewspace-2809964/,如需轉載,請註明出處,否則將追究法律責任。

相關文章