python 3.6:错误:需要一个类似字节的对象,而不是读取文件时的'str'

时间:2018-04-14 01:19:25

标签: python python-3.x pickle

我正在尝试使用以下代码读取文件。

filenames = os.listdir(path)
    data = []
    for file in filenames:
        file_path = os.path.join(path, file)
        print (file_path)
        with open(file_path, 'r') as f:
            try:
                soundId = os.path.splitext(file)[0]
                print (soundId)
                content = f.read()
                pp = pickle.loads(content)
                pp = np.asarray(pp)            
                data[soundId] = pp
            except Exception as e:
                print ("Error occurred" + str(e))

当我运行代码时,它给了我 发生错误需要类似字节的对象,而不是“str”

错误发生在pp = pickle.loads(内容)

还有其他类似问题,但没有一个问题有帮助。

我正在尝试读取音频文件的melspectogram数据。 Sample file i am trying to read

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

with open(file_path, 'rb') as f:代替with open(file_path, 'r') as f:

或使用content.encode()进行显式字节转换。

更新

您的问题与how-load-cv2-keypoint-and-descriptors-correctly-on-opencv-3-with-python-3

有关

使用下面的代码,它应该有效:

# blues.00000.pp
import pickle, numpy as np
pp_list = np.fromfile('blues.00000.pp')
print('pp_list type :' + str(type(pp_list)))
pp = []
data = dict()
soundID = 'ppFile1'
for i in range(len(pp_list)):
    temp = pp_list[i] * 1
    pp.append(temp)
pp = np.asarray(pp)
print('pp data : ' + str(pp))
data[soundID] = pp
print('ppdata dic :' + str(data))

输出

pp_list type :<class 'numpy.ndarray'>
pp data : [4.56259939e+257 4.78104776e+180 9.28824150e+242 ... 1.00603813e+165
 6.01326204e-067 1.55998657e-259]
ppdata dic :{'ppFile1': array([4.56259939e+257, 4.78104776e+180, 9.28824150e+242, ...,
       1.00603813e+165, 6.01326204e-067, 1.55998657e-259])}