gpt4 book ai didi

python-3.x - 加载 pickle 文件时出错

转载 作者:行者123 更新时间:2023-12-01 12:25:18 24 4
gpt4 key购买 nike

我在 python3 中加载 pickled 文件时遇到问题。见以下代码:

#!/usr/bin/env python3

import csv,operator
import pickle
import os.path

pathToBin = "foo/bar/foobar.bin"
pathToCSV = "foo/bar/foobar.csv"

if os.path.isfile(pathToBin):
print("Binary file already on harddrive, loading from there")
transactions = pickle.loads( open( pathToBin, "rb" ))
else:
csvIn = open(pathToCSV,'r')
reader = csv.reader(csvIn)
header = next(reader)
header = header[0].split(";")

print("Reading file")
transactions = []
for row in reader:
# read file.
# transactions contains now lists of strings: transactions = [ ["a","b","c"], ["a2","b2","c3"], ...]
print("Dumping python file to harddrive")
myPickleFile = open(pathToBin,'wb')
pickle.dump(transactions, myPickleFile, protocol=pickle.HIGHEST_PROTOCOL)

# do some more computation

保存文件没有任何问题。但是,加载它会给我以下错误:

transactions = pickle.loads( open( pathToBin, "rb" ))
TypeError: '_io.BufferedReader' does not support the buffer interface

由于我使用的是 python3,因此对字符串的处理方式有所不同。因此,我特别给出了“b”选项用于保存/加载。有人知道为什么这行不通吗?

最佳答案

你想使用load:

transactions = pickle.load(open( pathToBin, "rb" ))

从您打开的文件句柄中读取。 loads 接受 bytes 而不是文件句柄(意思是:加载“字符串”,现在在 python 3 升级字符串/字节处理后加载“字节”):

transactions = pickle.loads(open( pathToBin, "rb" ).read())

读取文件返回的字节。

在这种情况下,我会为您推荐第一个选项。第二种选择适用于更复杂的情况。

旁白:最好使用with上下文来控制文件何时关闭

with open( pathToBin,"rb") as f:
transactions = pickle.load(f)

关于python-3.x - 加载 pickle 文件时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40503229/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com