How to write a one character file using Python with mime type `text/plain`?

Viewed 455

How can I write a one character file in Python 3.8 that has the text/plain mime type?

Using Python, if I write one character to a file, the mime type of the file is application/octet-stream.

with open('file_from_python', 'w') as f: f.write('x')

(Note: Writing more than one character using the Python code above results in the text/plain mime type; the issue only occurs when you write less than two characters to a file).

Check the mime type of the python generated file using the following Linux command line:

file --mime-type file_from_python 
file_from_python: application/octet-stream

Using the Linux terminal, if I write one character to a file, the mime type of the file is text/plain.

echo "x" > file_from_bash

Check the mime type of the Linux terminal generated file using the following Linux command line:

file --mime-type file_from_bash
file_from_bash: text/plain
2 Answers

The file command is just applying heuristics to give a pretty good guess at the file type. It can't guess very well for a 1 byte file, so it gives up.

This bit of Python will produce a file identical to your bash command:

with open('file_from_python_text', 'w') as f: f.write('x\n')

Echo adds a newline.

Not sure how your app checks mime type but you should be aware that mime type is not really associated with file content. It's derrived from it (because that's the only sane way) but there's nothing preventing you say that i. e. JPG file is text/plain and plain text file is application/octet-stream or even image/jpeg. In other words you can easily tell what mime type it is based on your own rules if needed. Also file opinion is not definitive nor authoritative even if it's often right.

Related