简体   繁体   中英

Replace the delimiter of first line from ',' to ';' in csv file by Python

I got a weird csv file whose header's delimiter are ',' while common rows' delimiter is ';' which cause troubles for me to read and process it as a dictionary by python:

players.first_name,players.last_name,players.vis_name,players.player_id
Duje;Cop;Cop;8465
Dusan;Svento;Svento;8658
Markus;Henriksen;Henriksen;7687

I wonder if I can replace only the header's delimiter with ';' or if there is a way to read such csv file to be dictionary without changing the header's delimiter?

BTW: I am using Python 2.7.12 with Anaconda 4.0.0 via IDE PyCharm

You can read the first line with a classical csv reader, just to get field names, then continue reading with the dictionary reader, changing the separator to ; at this point.

import csv

with open("input.csv") as f:
    cr = csv.reader(f, delimiter=",")
    fieldnames = next(cr)

    cr = csv.DictReader(f,fieldnames=fieldnames,delimiter=";")

    for d in cr:
        print(d)

result:

{'players.player_id': '8465', 'players.vis_name': 'Cop', 'players.first_name': 'Duje', 'players.last_name': 'Cop'}
{'players.player_id': '8658', 'players.vis_name': 'Svento', 'players.first_name': 'Dusan', 'players.last_name': 'Svento'}
{'players.player_id': '7687', 'players.vis_name': 'Henriksen', 'players.first_name': 'Markus', 'players.last_name': 'Henriksen'}

PS: my previous solution involved reading/writing to a StringIO , but the current one is much more elegant.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM