Replace the delimiter of first line from ',' to ';' in csv file by Python
<p>I got a weird csv file whose header's delimiter are <strong>','</strong> while common rows' delimiter are <strong>';'</strong> which cause troubles for me to read and process it as dictionary by python:</p>

<pre><code>players.first_name,players.last_name,players.vis_name,players.player_id
Duje;Cop;Cop;8465
Dusan;Svento;Svento;8658
Markus;Henriksen;Henriksen;7687
</code></pre>

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

<p><em>BTW:</em> I am using Pyhton 2.7.12 with Anaconda 4.0.0 via IDE PyCharm</p>

<p><em>Any help will be appreciated, thank you</em></p>

<p>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 <code>;</code> at this point.</p>

<pre><code>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)
</code></pre>

<p>result:</p>

<pre><code>{'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'}
</code></pre>

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

python csv delimiter