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)

4
  • It would seem that the OS is tracking the file type. Which OS? Commented May 9, 2022 at 18:12
  • OS: Ubuntu 18.04 Commented May 9, 2022 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. Commented May 9, 2022 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. Commented May 12, 2022 at 6:21

2 Answers 2

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

This will help.

Sign up to request clarification or add additional context in comments.

Comments

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.