迭代单个字节然后将其保存到文件中而不改变内容

问题描述

我有一个从 API 返回的字节字符串并存储在 response.content

对于小内容,我可以使用以下代码将其保存到文件中没有问题

with open(save_path,'wb') as save_file:
    save_file.write(response.content)

但是对于较大的文件,它会导致内存错误,因此我尝试不使用此代码一次读取所有内容

with open(save_path,'wb') as save_file:
    for x in response.content: 
        save_file.write(bytes(x)) #the x from iteration seem to be converted to int so I convert it back

但是上面的方法似乎改变了内容,因为它不再与另一个库兼容(在我laspy尝试读取保存的文件时,出现laspy.util.laspyException: Invalid format: h0.0错误

我该怎么做?

解决方法

我发现您在使用 bytes(x) 时遇到了问题。将其更改为 x.to_bytes(1,'big') 解决您的问题

使用下面的代码来揭示什么区别

a = b'\xcf\x84o\xcf\x81\xce\xbdo\xcf\x82'
a.decode('utf-8') # τoρνoς

with open('./save.txt','wb') as save_file:
    for i in a:
        print(i.to_bytes(1,'big')) # write it to file,not the others
        print(i)
        print(bytes(i))
        print('----')

enter image description here