# Python Get Text File Character Encoding: A Beginner Guide – Python Tutorial

By | March 24, 2020

Text file, such as .txt, .csv, .xml et al, is encoded by special character encoding (utf-8, gbk, gb2312, …). How to get the character encoding of a text file? We will use a simple python example to show you how to do.

Prepare a text file

We prepare a csv file in this example, this file is called:601988.csv

Get the character encoding of a text file

There is an easy way to get the character encoding of a text file in python. Here is an example code.

with open("data/601988.csv") as f:
print(f.encoding)

Run this code, we will get the character encoding of this csv file is:

cp936

To understand python with statement, you can view:

Understand Python With Statement: A Beginner Guide – Python Tutorial