1

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.

enter image description here

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)

Nandha
  • 752
  • 1
  • 12
  • 37
  • It would seem that the OS is tracking the file type. Which OS? – Mark Ransom May 09 '22 at 18:12
  • OS: Ubuntu 18.04 – Nandha May 09 '22 at 18:16
  • 1
    It's referring to the MIME type. There probably is some way to change it, but you can also safely ignore it,. It has no effect on the contents of the file. – Alexander May 09 '22 at 21:11
  • We are uploading the file to some other service which is not accepting this modified file. If we upload the file without changing anything, the service accepts the file. So we could not ignore it. – Nandha May 12 '22 at 06:21

2 Answers2

3
with open('filename', 'w', encoding='utf-16') as fw:
    fw.write('ee')

This will help.

1

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)