Skip to content Skip to sidebar Skip to footer

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 s

Solution 1:

The answer is easier than you think. You just need to set the delimiter for csv.writer:

import csv

row = #your datawithopen("temp.csv", mode="rU") as infile:
    reader = csv.reader(infile, dialect="excel")    
    withopen("temp2.txt", mode="w") as outfile:
        writer = csv.writer(outfile, delimiter=':')
        writer.writerows(rows)

You're line trying to replace , with : wasn't going to do anything because the row had already been processed by csv.reader.

Solution 2:

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.

Solution 3:

I will build my answer on @Sylhare's answer. In python3, the 'U' mode is deprecated. So, the following solution worked for me:

import csv

reader = csv.reader(open("input.csv", newline=None), delimiter=',')
writer = csv.writer(open("output.csv", 'w'), delimiter=':')
writer.writerows(reader)

Solution 4:

I'm writing csv files from JSON raw data and noticed that the DictWriter module also supports different delimiters. Example:

withopen('file_1.csv', 'w', encoding="utf-8-sig", newline = '') as myfile:
    wr = csv.DictWriter(myfile, fieldnames = table_fields, delimiter=';')
    wr.writeheader()
    wr.writerows(# my data #)

Solution 5:

Assuming that the CSV is comma delimited, and you want to replace commas in each entry, I believe the issue is replacing the wrong item:

forrowsin reader:
    for parsed_item inrows:
        parsed_item = parsed_item.replace(',', ':') # Change rowsto parsed_item
        writer.writerow(parsed_item)

Post a Comment for "Python Parse Csv File - Replace Commas With Colons"