簡體   English   中英

I/O 為什么我的代碼總是拋出錯誤

[英]I/O why my code is always throwing and error

我將數據存儲在二進制文件中。

在此處輸入代碼

代碼 1——

import pickle as p

d = []

for i in range(3):
 
   d1 = []
    st = input("enter student name")
    rl = int(input("student roll no"))
    d1.append(st)
    d1.append(rl)
    d.extend(d1)

f = open("alex.dat", "wb")
p.dump(d,f)
f.close()

然后我打印了

代碼2——

import pickle as p
d = []
f = open("students.dat", "rb")
while f:
    try:
        d = p.load(f)
        print(d)
    except EOFError:
        f.close()

output -- ['admin', 22, 'momo', 21, 'sudhanshu', 323] Traceback(最近一次通話最后):文件“C:\Users\admin\AppData\Roaming\JetBrains\PyCharmCE2021.3\scratches \scratch_2.py",第 6 行,在 d = p.load(f) ValueError: peek of closed file

為什么值錯誤?

正如@Maurice Mayer 所說,while Condition 正在破壞您的代碼

您正在將代碼 1 中的所有內容寫入一個文件中,因此您只需加載該文件一次。 檢查已關閉的文件對象正在破壞您的代碼 2

import pickle as p
d = None # Just to be sure
f = open("students.dat", "rb")

try:
    d = p.load(f)
    print(d)
except EOFError:
    f.close()

這應該工作

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM