惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

博客园_首页
H
Help Net Security
量子位
The Cloudflare Blog
博客园 - Franky
博客园 - 聂微东
博客园 - 司徒正美
Last Week in AI
Last Week in AI
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
Apple Machine Learning Research
Apple Machine Learning Research
宝玉的分享
宝玉的分享
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
有赞技术团队
有赞技术团队
罗磊的独立博客
GbyAI
GbyAI
雷峰网
雷峰网
T
The Blog of Author Tim Ferriss
Martin Fowler
Martin Fowler
S
SegmentFault 最新的问题
美团技术团队
阮一峰的网络日志
阮一峰的网络日志
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
U
Unit 42
MongoDB | Blog
MongoDB | Blog

jdhao's digital space

Conversion between base64 and OpenCV or PIL Image 腾讯云对象存储博客图床开启 CDN 加速(不需要购买额外域名) Search and Replace in Multiple Files in Vim/Neovim Change Table Column Width in LaTeX Image or Table Side by Side in LaTeX LaTeX 并排显示图像或表格 Firenvim: Neovim inside Your Browser Content inside HTML tags missing in Latest Hugo? Creating Markdown Front Matter with Ultisnips Labelme JSON 标注格式转 voc XML 格式 Nifty Nvim Techniques That Make My Life Easier -- Series 6 macOS 下如何为视频制作字幕 Running Command Asynchronously inside Neovim Resolving Merge Conflict after Git Stash Pop Pylint: command not found? A Hands-on Experience with Neovim's Built-in LSP Support How to Convert PDF to Images with Imagemagick 互联网上常用缩略语集锦 File Backup in Neovim Converting PDF Pages to Images with Poppler Nifty Nvim Techniques That Make My Life Easier -- Series 5 Neovim Configuration for System-wide Use How to sort a list of tuple or list in Python -- lambda or itemgetter? Building A Vim Statusline from Scratch 人类第一颗原子弹爆炸始末 Distributed Training in PyTorch with Horovod Learning Expect Programming Essential Knowledge about SSH Nifty LaTeX Techniques -- Series 1 更改 Adsense 邮寄地址,重新寄送 PIN
Reading and Writing Text Files on Windows
2018-12-03 · via jdhao's digital space

If you are using Python 3 on Windows, you may have seen a Unicode decoding error when opening files in UTF-8 format:

UnicodeDecodeError: ‘gbk’ codec can’t decode byte 0xaf in position 5: illegal multibyte sequence

If you read the same file on Linux or macOS, you will find that this file can be opened without any error. Why is there a difference? It has something to do with the default encoding Python chooses to use on different platforms.

The reason and the solution#

Reading UTF-8 files#

To show the default encoding used by Python on your platform, use the following snippet:

import locale
locale.getpreferredencoding()

The method locale.getpreferredencoding() is used to get the encoding for text files on the system. On Linux, the output is UTF-8 and on my Windows (a Chinese simplified version of Windows 10 Pro), the output is cp936, which means that UTF-8 is used as the default encoding on Linux and cp936 is used as the default encoding on Windows1.cp936 is the abbreviation for “Microsoft code page 936”, which encodes all the characters in the GBK character set.

The solution to this issue is quite simple. If you are sure that the file to read is encoded in UTF-8, you can use encoding="utf-8" in the built-in open() method:

with open("test.txt", "r", encoding="utf-8"):
    text = f.read()

The Python 3 official documentation for encoding parameter says:

encoding is the name of the encoding used to decode or encode the file. This should only be used in text mode. The default encoding is platform dependent (whatever locale.getpreferredencoding() returns), but any text encoding supported by Python can be used. See the codecs module for the list of supported encodings.

Writing UTF-8 files#

You may wonder that when you write non-ASCII characters to files on Windows, you haven’t encountered any issues related to encoding. The reason is probably that the gbk codec used can encode the characters by chance. If you use characters not in the GBK character set, you will see encoding errors. To verify this, use the following snippet:

with open("test.txt", "w") as f:
    f.write("조선말")

If you run the above script on Windows, you may see the following error message:

UnicodeEncodeError Traceback (most recent call last) in () 1 with open(“test.txt”, “w”) as f: —-> 2 f.write(“조선말”) 3

UnicodeEncodeError: ‘gbk’ codec can’t encode character ‘\uc870’ in position 0: illegal multibyte sequence

To solve this issue and save files in UTF-8 encoding, you should use encoding="utf-8" when writing texts to files.

References#