Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

The Application of python programming language in operating File coding format

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

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.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report