Friday, 15 March 2013

Read and Write CSV files including unicode with Python 2.7 -


I am new to Python, and I have a question about using Python for reading and writing CSV files is. My files include Germany, French etc. According to my code, files can be read correctly in python, but when I write it in a new CSV file, Unicode becomes some strange character.

The data is like: Enter image details here

And my code is:

  import csv f = open ('xxx.csv', 'rb') reader = csv.reader (f) wt = open ('lll.csv', ' Wb ') Author = csv.writer (wt, quoting = csv.QUOTE_ALL) wt.close () f.close ()   

And the result is as follows:  Enter image details here

Would you please tell me what should I do to solve the problem? Thanks a lot!

Ensure that you encode and decode as appropriate.

This example will round up some example text in a CSV file in UTF-8 and return to display:

  # - * - coding: UTF -8 - * - Import CSV test = {'German': [U'straÃÆ'à ¢ â,¬Å¡Ãƒâ € šÃ, · 'u'auslösen', u'zerstà ¶ren '],' French ': [U'français', u'amà © ricaine ', u'ÃÆ'à  â € ™ Ã⠀ šÃ, ©'], 'Chinese': [U'Auura ???? Ç ???? ', u'a ?? ± è èª ?? ', U'KG? One' ???? ºº ']} (' / tmp / utf.csv ',' w ') in the form of a fountain: author = csv.writer (fout) writer.writerows ([tests.keys ()]) For (* tests.values ​​()): Row = [s.encode (in line 's utf-8']] as author. Author ([line]) with open ('/ tmp / utf.csv', 'r') as the wing: reader = csv reader for line in reader: fmt = u '{: & Lt; 15} '* len (temp) print fmt.format (* [s.decode (' utf-8 ') for temporary)]   

Print: < Pre> German Chinese French Strai ?? Eaaaaa ???? Ç ???? France els eslassen è ?? ± èª ?? AMA © Risen Xerver urene ¾ one ???? AAS pius

No comments:

Post a Comment