Reading a UTF8 CSV file with Python

后端 未结 9 1622
青春惊慌失措
青春惊慌失措 2020-11-22 12:20

I am trying to read a CSV file with accented characters with Python (only French and/or Spanish characters). Based on the Python 2.5 documentation for the csvreader (http://

9条回答
  •  执念已碎
    2020-11-22 12:51

    Python 2.X

    There is a unicode-csv library which should solve your problems, with added benefit of not naving to write any new csv-related code.

    Here is a example from their readme:

    >>> import unicodecsv
    >>> from cStringIO import StringIO
    >>> f = StringIO()
    >>> w = unicodecsv.writer(f, encoding='utf-8')
    >>> w.writerow((u'é', u'ñ'))
    >>> f.seek(0)
    >>> r = unicodecsv.reader(f, encoding='utf-8')
    >>> row = r.next()
    >>> print row[0], row[1]
    é ñ
    

    Python 3.X

    In python 3 this is supported out of the box by the build-in csv module. See this example:

    import csv
    with open('some.csv', newline='', encoding='utf-8') as f:
        reader = csv.reader(f)
        for row in reader:
            print(row)
    

提交回复
热议问题