Convert encoding of a text file from utf-8 to ansi or unicode in python

23,060

Solution 1

Try this

#read input file
with codecs.open('USERS.CSV', 'r', encoding = 'latin-1') as file:
lines = file.read()  

#write output file
with codecs.open('1_UserPython.CSV', 'w', encoding = 'utf_8_sig') as file:
file.write(lines)

Solution 2

To convert a file from utf8 to cp1252:

import io

with io.open(src_path, mode="r", encoding="utf8") as fd:
    content = fd.read()
with io.open(dst_path, mode="w", encoding="cp1252") as fd:
    fd.write(content)
Share:
23,060
narges
Author by

narges

Updated on August 25, 2020

Comments

  • narges
    narges over 3 years

    I have a text file with utf-8 encoding. I want to change it's unicode to ANSI or unicode automatically in python. Is it possible? How can i do it?