Python read csv - BOM embedded into the first key

前端 未结 2 1279
日久生厌
日久生厌 2020-11-30 09:34

I\'m using Python 2.7.12. With this code snippet I\'m saving a utf-8 csv file. I wrote the BOM (byte order mark) at the beginning of the file.

import codecs
         


        
相关标签:
2条回答
  • 2020-11-30 10:13

    In Python 3, the built-in open function is an alias for io.open.

    All you need to open a file encoded as UTF-8 with BOM:

    open(path, newline='', encoding='utf-8-sig')
    

    Example

    import csv
    
    ...
    
    with open(path, newline='', encoding='utf-8-sig') as csv_file:
        reader = csv.DictReader(csv_file, dialect='excel')
        for row in reader:
            print(row['first_name'], row['last_name'])
    
    0 讨论(0)
  • 2020-11-30 10:19

    You have to tell open that this is UTF-8 with BOM. I know that works with io.open:

    import io
    
    .
    .
    .
    inputFile = io.open("test.csv", "r", encoding='utf-8-sig')
    .
    .
    .
    

    And you have to open the file in text mode, "r" instead of "rb".

    0 讨论(0)
提交回复
热议问题