I am trying to create a text file in csv format out of a PyQt4 QTableWidget
. I want to write the text with a UTF-8 encoding because it contains special characters. I use following code:
import codecs ... myfile = codecs.open(filename, 'w','utf-8') ... f = result.table.item(i,c).text() myfile.write(f+";")
It works until the cell contains a special character. I tried also with
myfile = open(filename, 'w') ... f = unicode(result.table.item(i,c).text(), "utf-8")
But it also stops when a special character appears. I have no idea what I am doing wrong.
UTF-8, or "Unicode Transformation Format, 8 Bit" is a marketing operations pro's best friend when it comes to data imports and exports. It refers to how a file's character data is encoded when moving files between systems.
One easy way to change excel ANSI encoding to UTF-8 is the open the . csv file in notepad then select File > Save As. Now at the bottom you will see encoding is set to ANSI change it to UTF-8 and save the file as a new file and then you're done.
and CSV files. Simple CSV files do not support Unicode/UTF-8 characters. This is a limitation of the CSV format and not something that can be changed in DEAR.
Click Tools, then select Web options. Go to the Encoding tab. In the dropdown for Save this document as: choose Unicode (UTF-8). Click Ok.
It's very simple for Python 3.x (docs).
import csv with open('output_file_name', 'w', newline='', encoding='utf-8') as csv_file: writer = csv.writer(csv_file, delimiter=';') writer.writerow('my_utf8_string')
For Python 2.x, look here.
From your shell run:
pip2 install unicodecsv
And (unlike the original question) presuming you're using Python's built in csv
module, turn import csv
into import unicodecsv as csv
in your code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With