I am getting the error:"UnsupportedOperation: read"

I am getting the error:"UnsupportedOperation: read"

import pickle

#writing into the file

f = open("essay1.txt","ab+")

list1 = ["Aditya","Arvind","Kunal","Naman","Samantha"]

list2 = ["17","23","12","14","34"]

zipfile = zip(list1,list2)

print(zipfile)

pickle.dump(zipfile,f)

f.close()

#opening the file to read it 

f = open("essay1","ab")

zipfile = pickle.load(f)

f.close()

输出为:

runfile('E:/Aditya Singh/Aditya Singh/untitled3.py', wdir='E:/Aditya Singh/Aditya Singh')
<zip object at 0x0000000008293BC8>
Traceback (most recent call last):

  File "E:\Aditya Singh\Aditya Singh\untitled3.py", line 21, in <module>
    zipfile = pickle.load(f)

UnsupportedOperation: read

你有essay1文件吗?或 essay1.txt?

这试图在没有扩展名的情况下打开。

f = open("essay1","ab")

所以无法读取。

您的代码有两个问题:

  • 您正在打开文件进行写入而不是读取。
  • 您正在使用不同的文件名进行读取和写入。

这是一个有效的版本:

import pickle

#writing into the file
f = open("essay1.txt","wb")
list1 = ["Aditya","Arvind","Kunal","Naman","Samantha"]
list2 = ["17","23","12","14","34"]
zipfile = zip(list1,list2)
print(zipfile)
pickle.dump(zipfile,f)
f.close()

#opening the file to read it 

f = open("essay1.txt","rb")
zipfile = pickle.load(f)
print(zipfile)
f.close()

您在尝试打开文件的行中忘记了文件扩展名 .txt,并且您以 append 模式打开它,这就是返回对象的原因没有 readreadline 方法(pickle.load 需要)。我还建议使用 with keyword 而不是手动关闭文件。

import pickle

#writing into the file

with open("essay1.txt","ab+") as f:
    list1 = ["Aditya","Arvind","Kunal","Naman","Samantha"]
    list2 = ["17","23","12","14","34"]
    zipfile = zip(list1,list2)
    print(zipfile)
    pickle.dump(zipfile,f)

#opening the file to read it
with open("essay1.txt", "rb") as f:
    zipfile = pickle.load(f)

for item in zipfile:
    print(item)

输出:

<zip object at 0x7fa6cb30e3c0>
('Aditya', '17')
('Arvind', '23')
('Kunal', '12')
('Naman', '14')
('Samantha', '34')