[英]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 ';' 我得到了一个奇怪的csv文件,其标头的定界符为“,”而普通行的定界符为“;”。 which cause troubles for me to read and process it as a dictionary by python: 这给我带来麻烦,无法通过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? 或者是否有一种方法可以读取这样的csv文件作为字典而不更改标题的定界符?
BTW: I am using Python 2.7.12 with Anaconda 4.0.0 via IDE PyCharm 顺便说一句:我正在通过IDE PyCharm将Python 2.7.12与Anaconda 4.0.0一起使用
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 ;
您可以使用传统的csv阅读器阅读第一行,仅获取字段名称,然后继续使用字典阅读器阅读,将分隔符更改为;
即可;
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. PS:我以前的解决方案涉及到对StringIO
读取/写入,但是当前的解决方案要优雅得多。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.