Python parse csv file - replace commas with colons

前端 未结 6 1266
孤独总比滥情好
孤独总比滥情好 2020-12-11 02:50

I suspect this is a common problem, but I counldn\'t seem to locate the answer. I am trying to remove all commas from a csv file and replace them with colons. I would normal

6条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-11 03:05

    If you are looking to read a csv with comma delimiter and write it in another file with semicolon delimiters. I think a more straightforward way would be:

    reader = csv.reader(open("input.csv", "rU"), delimiter=',')
    writer = csv.writer(open("output.csv", 'w'), delimiter=';')
    writer.writerows(reader)
    

    I find this example much easier to understand than with the with open(...). Also if you work with file using comma and semicolon as delimiters. You can use the Sniffer of the csv file to detect which delimiter is used before reading the file (example in the link).

    Also if you want to rewrite in the same file, check this stackoverflow answer.

提交回复
热议问题