How to read a CSV File delimited by '\x01' and create a dictionary in python

前端 未结 2 1660
醉酒成梦
醉酒成梦 2021-01-29 08:00

I have a requirement to read a CSV file which is \\x01 (^A) delimited and create a dictionary for my lookup for processing my business logic further. My input file

2条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-29 08:06

    You can register a custom dialect that uses that character as a separator as seen in this answer.

    import csv
    
    class custom_sep(csv.excel):
        delimiter = chr(0x01)
    csv.register_dialect("custom_sep", custom_sep)
    
    data = """col1\x01col2\x01col3
    foo\x01bar\x01baz
    moo\x01mee\x01mah"""
    
    data = csv.DictReader((x.strip() for x in data.split('\n')), dialect="custom_sep")
    for row in data:
        print row
    

提交回复
热议问题