Santanu Guha
Santanu Guha

Reputation: 101

How to set encoding as 'ANSI' using Python?

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 ?

Upvotes: 4

Views: 17079

Answers (3)

Tomalak
Tomalak

Reputation: 338248

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.

Upvotes: 7

Gabriel Melo
Gabriel Melo

Reputation: 521

Try one of the ANSI encodings:

encoding='cp1252'

For further information, take a look here

Upvotes: 3

Emily
Emily

Reputation: 1096

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

Upvotes: 4

Related Questions