python 3.6: Error: a bytes-like object is required, not 'str' when reading a file

python 3.6: Error: a bytes-like object is required, not 'str' when reading a file

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

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

还有其他类似问题,但 none 个问题有所帮助。

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

我该如何解决这个问题?

with open(file_path, 'rb') as f: 而不是 with open(file_path, 'r') as f:

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

更新

您的问题与

有关

使用下面的代码,它应该可以工作:

# 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])}