[英]How to write a one character file using Python with mime type `text/plain`?
How can I write a one character file in Python 3.8 that has the text/plain
mime type?如何在 Python 3.8 中编写一个具有
text/plain
mime 类型的单字符文件?
Using Python, if I write one character to a file, the mime type of the file is application/octet-stream
.使用 Python,如果我将一个字符写入文件,则文件的 mime 类型为
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). (注意:使用上面的 Python 代码写入多个字符会导致
text/plain
mime 类型;仅当您向文件写入少于两个字符时才会出现此问题)。
Check the mime type of the python generated file using the following Linux command line:使用以下 Linux 命令行检查 python 生成文件的 mime 类型:
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
.使用 Linux 终端,如果我将一个字符写入文件,则文件的 mime 类型为
text/plain
。
echo "x" > file_from_bash
Check the mime type of the Linux terminal generated file using the following Linux command line:使用以下 Linux 命令行检查 Linux 终端生成文件的 mime 类型:
file --mime-type file_from_bash
file_from_bash: text/plain
The file command is just applying heuristics to give a pretty good guess at the file type. file命令只是应用启发式方法来很好地猜测文件类型。 It can't guess very well for a 1 byte file, so it gives up.
它不能很好地猜测一个 1 字节的文件,所以它放弃了。
This bit of Python will produce a file identical to your bash command: Python 的这一位将生成与您的 bash 命令相同的文件:
with open('file_from_python_text', 'w') as f: f.write('x\n')
Echo adds a newline. Echo 添加一个换行符。
Not sure how your app checks mime type but you should be aware that mime type is not really associated with file content.不确定您的应用如何检查 mime 类型,但您应该知道 mime 类型与文件内容并没有真正关联。 It's derrived from it (because that's the only sane way) but there's nothing preventing you say that ie JPG file is
text/plain
and plain text file is application/octet-stream
or even image/jpeg
.它是由它派生的(因为这是唯一理智的方式),但没有什么能阻止你说 JPG 文件是
text/plain
而纯文本文件是application/octet-stream
甚至是image/jpeg
。 In other words you can easily tell what mime type it is based on your own rules if needed.换句话说,如果需要,您可以根据自己的规则轻松判断它是什么 mime 类型。 Also
file
opinion is not definitive nor authoritative even if it's often right. file
意见也不是确定的,也不是权威的,即使它通常是正确的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.