Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python parse csv file - replace commas with colons

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 normally use sed or vi for this, but I need to use a purely python implementation. Here is what I have come up with so far:

import csv

with open("temp.csv", mode="rU") as infile:
    reader = csv.reader(infile, dialect="excel")    
    with open("temp2.txt", mode="w") as outfile:
        writer = csv.writer(outfile)
        for rows in reader:
            for parsed_item in rows:
                parsed_item = rows.replace(',', ':') # I can't do this with a list!
                writer.writerow(parsed_item)

Can anyone help me out with how to do this? Thanks in advance for your help.

like image 721
drbunsen Avatar asked Jul 08 '11 20:07

drbunsen


People also ask

How do you change a comma separator to a semicolon in a csv file?

Indicate separator directly in CSV file For this, open your file in any text editor, say Notepad, and type the below string before any other data: To separate values with comma: sep=, To separate values with semicolon: sep=;

How do I remove a comma from a csv file in Python?

Extra commas in csv file are nothing but missing value, if the commas are extreme right you can just use rstrip () on read csv file.


1 Answers

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", "r"), 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.

like image 183
Sylhare Avatar answered Oct 15 '22 10:10

Sylhare