简体   繁体   English

I/O 为什么我的代码总是抛出错误

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

i stored data in a binary file.我将数据存储在二进制文件中。

enter code here在此处输入代码

code 1--代码 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()

and then i printed然后我打印了

code 2--代码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 (most recent call last): File "C:\Users\admin\AppData\Roaming\JetBrains\PyCharmCE2021.3\scratches\scratch_2.py", line 6, in d = p.load(f) ValueError: peek of closed file 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

why valueError?为什么值错误?

As @Maurice Mayer stated the while Condition is breaking your Code正如@Maurice Mayer 所说,while Condition 正在破坏您的代码

You are writing in Code 1 everything in one file so you need just to load the file once.您正在将代码 1 中的所有内容写入一个文件中,因此您只需加载该文件一次。 Checking the file-object which is already closed is breaking your Code 2检查已关闭的文件对象正在破坏您的代码 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()

This should work这应该工作

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM