当我运行代码时:
import pickle
ofname = open(r"ch05\dataset_small.pkl", 'rb')
(x, y) = pickle.load(ofname)我在运行上面的代码时遇到的错误是:
'ascii' codec can't decode byte 0xac in position 6: ordinal not in range(128)如何修复此错误?
发布于 2021-12-15 18:47:31
此问题是由于python2.x cPickle与python3.x泡菜不兼容造成的。
(x, y) = pickle.load(ofname, encoding='latin1)以下是两个成功的、序列化和反序列化数据的不同应用程序:
# user.py
class User:
    def __init__(self,name,age):
        self.name = name
        self.age = age
    
    def show(self):
        print(f'Name: {self.name}\nAge: {self.age}\n')# picker.py
import pickle, user
with open('user.dat','wb') as f:
    n = int(input("Enter number of users: "))
    for i in range(n):
        name = input("Enter Name: ")
        age = input("Enter Age: ")
        ob = user.User(name,age)
        pickle.dump(ob, f)
        
print('Done')# unpicker.py
import pickle, user
with open('user.dat','rb') as f:
    while True:
        try:
            # Note that the encoding argument is used in the picker.load() method.
            obj = pickle.load(f, encoding='latin1')
            obj.show()
        except EOFError:
            print('Done')
            breakhttps://stackoverflow.com/questions/70368805
复制相似问题