Changing encoding in csv file through python UTF-8 to UTF-16

1.7k views Asked by At

How do you change the encoding through a python script?

I've got some files that I'm looping doing some other stuff. But before that I need to change the encoding on each file from UTF-8 to UTF-16 since SQL server does not support UTF-8

Tried this, but not working.

data = "UTF-8 data"
udata = data.decode("utf-8")
data = udata.encode("utf-16","ignore")

Cheers!

1

There are 1 answers

0
Robᵩ On BEST ANSWER

If you want to convert a file from utf-8 encoding to a file with utf-16 encoding, this script works:

#!/usr/bin/python2.7

import codecs
import shutil

with codecs.open("input_file.utf8.txt", encoding="utf-8") as input_file:
    with codecs.open(
            "output_file.utf16.txt", "w", encoding="utf-16") as output_file:
        shutil.copyfileobj(input_file, output_file)