Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set encoding as 'ANSI' using Python?

Tags:

python

ansi

I am using Python 3.7.4 version. I want to set the encoding as 'ANSI' at the time of reading a text file and also writing a text file.

I another case I read a file by providing 'utf-8' ( please find code snippet below ) as encoding but in case of 'ANSI' I am not finding any value to provide as encoding.

code snippet :

content = open(fullfile , encoding='utf-8').readlines()  

What should be done to set encoding as 'ANSI' in Python ?

like image 535
Santanu Guha Avatar asked Nov 07 '25 13:11

Santanu Guha


2 Answers

There is no "ANSI"-encoding. "ANSI" means "whatever the default single-byte encoding happens to be on your machine" – the term "ANSI" is inherently ambiguous. This means you must specify an actual encoding when reading the file.

For Windows machines in the Western Europe region, "ANSI" typically refers to Windows-1252. Other regions differ, but also your machine configuration might be different.

Python refers to Windows-1252 as cp1252. If that really is the encoding your file is in depends on the file itself, and can only be found out by looking at it.

Often text editors (not Notepad, real text editors) have an option to interpret a file in various encodings. Pick the one that makes the data look right (pay attention to accented characters) and then find out Python's name for it.

like image 184
Tomalak Avatar answered Nov 10 '25 03:11

Tomalak


ANSI is not actually an encoding, you probably mean Windows-1252, which Python supports as 'cp1252'.

like image 44
Emily Avatar answered Nov 10 '25 04:11

Emily



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!