'Python Write to file as binary (application-octet stream) file type format
We have a file without any extension. This file is given by client and used by another program Sample content of the file is given below. It is just json content.
{"pid":23,"list":[{"pid":11}]}
From properties we can see that,this file is of type Binary (application/octet-stream) . Now we will read this file and load it as json and do some modifications to the this and finally we will write it to a new result file.
import json
r = {"a": 2, "B": 3}
with open("jres", "wb") as w:
txt = json.dumps(r, separators=(',', ':'))
w.write(txt.encode())
After writing to the file, the file type is changed as plain/text. How to create result file with same file type as previous one? If we use the result file (plain/text), the application is not accepting it. Hence we are trying to write the file in the accepted format which is Binary (application/octet-stream)
Solution 1:[1]
with open('filename', 'w', encoding='utf-16') as fw:
fw.write('ee')
This will help.
Solution 2:[2]
you can try encoding the content before writing to file stream
with open('filename', 'wb') as fw:
content = 'ee'.encode('utf-16')
fw.write(content)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Susil Shanmugam |
Solution 2 | Santhosh Kumar |