Get the App
SLTechnology News&Howtos  ›  Development  › 

The Application of python programming language in operating File coding format

Shulou Source: shulou.com Published: 2022-06-02 23:31:20 09月14日 Update

In this issue, Xiaobian will bring you about the application process of python programming language in the operation file encoding format. The article is rich in content and analyzed and described from a professional perspective. After reading this article, I hope you can gain something.

Create a file test.txt, file format ANSI, content:abc Chinese python to read

# coding=gbk print open("Test.txt").read()

Result: abc Chinese file format changed to UTF-8: obviously, here need to decode:

# coding=gbk import codecs print open("Test.txt").read().decode("utf-8")

Result: abc Chinese test.txt I edited with Editplus, but when I edited it with Notepad that comes with Windows and stored it in UTF-8 format, the error occurred when running:

Traceback (most recent call last):

File "ChineseTest.py", line 3, in

print open("Test.txt").read().decode("utf-8")

UnicodeEncodeError: 'gbk' codec can't encode

character u'\ufeff' in position 0: illegal multibyte

sequence

It turns out that some software, such as notepad, when saving a file encoded in UTF-8, inserts three invisible characters (0xEF 0xBB 0xBF, or BOM) at the beginning of the file. So we need to remove these characters ourselves when reading, and the codecs module in python defines this constant:

# coding=gbk import codecs data = open("Test.txt").read() if data[:3] == codecs.BOM_UTF8: datatar = data[3:] print data.decode("utf-8") The above is the application process of Python programming language in the operation file encoding format shared by everyone. If there is any similar doubt, please refer to the above analysis for understanding. If you want to know more about it, please pay attention to the industry information channel.

Tags: File format coding content UTF-8 utf-8 Chinese programming language language process application programming character result analysis three professional small and medium rich in content local Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Microsoft Shulou Information Docker MySQL Xiaomi