Python parse csv file - replace commas with colons

2019-01-12 09:07发布

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.

4条回答
女痞
2楼-- · 2019-01-12 09:53

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

import csv

row = #your data

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, 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.

查看更多
我欲成王,谁敢阻挡
3楼-- · 2019-01-12 09:58

If you're just replacing commas with colons, you don't need to use a csv parser at all.

with open("file.csv", 'r') as f:
    with open("temp.csv", 'w') as t:
        for lines in f:
            new_line = line.replace(",",":")
            t.write(new_line)

The only caveat is that you can't have commas elsewhere in the csv file.

查看更多
啃猪蹄的小仙女
4楼-- · 2019-01-12 10:06

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.

查看更多
欢心
5楼-- · 2019-01-12 10:07

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:

for rows in reader:
    for parsed_item in rows:
        parsed_item = parsed_item.replace(',', ':') # Change rows to parsed_item
        writer.writerow(parsed_item)
查看更多
登录 后发表回答