【问题标题】:I am getting the error:"UnsupportedOperation: read"我收到错误消息:“UnsupportedOperation:读取”
【发布时间】:2020-07-14 07:07:41
【问题描述】:
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

【问题讨论】:

  • 为什么要使用ab模式打开文件?
  • 会不会是文件名有误?你写了essay1,但它看起来应该是essay1.txt。

标签: python pickle file-handling


【解决方案1】:

您在尝试打开文件的行中忘记了文件扩展名 .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')

【讨论】:

    【解决方案2】:

    你有essay1文件吗?还是essay1.txt?

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

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

    所以无法读取。

    【讨论】:

      【解决方案3】:

      您的代码有两个问题:

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

      这是一个可行的版本:

      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()
      

      【讨论】:

      • @AdityaSingh 如果答案解决了您的问题,请考虑通过单击左侧的勾号来接受它。
      猜你喜欢
      • 1970-01-01
      • 2021-08-10
      • 2011-08-29
      • 2018-05-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-16
      • 2015-01-25
      相关资源
      最近更新 更多