EOFError: Ran out of input

使用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 {}

參考:Why do I get “Pickle - EOFError: Ran out of input” reading an empty file?

發佈了56 篇原創文章 · 獲贊 53 · 訪問量 25萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章