Python解析csv文件 - 用冒号替换逗号 [英] Python parse csv file - replace commas with colons
问题描述
我怀疑这是一个常见的问题,但我似乎找不到答案。我试图从csv文件中删除所有的逗号,并用冒号替换它们。我通常使用sed或vi这个,但我需要使用纯python实现。这是我到目前为止所得到的:
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.
推荐答案
答案比你想象的容易。您只需要为 csv.writer
设置分隔符:
The answer is easier than you think. You just need to set the delimiter for csv.writer
:
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, delimiter=':')
writer.writerows(rows)
您正试图替换,
c>:不会做任何事情,因为该行已经被 csv.reader
处理。
You're line trying to replace ,
with :
wasn't going to do anything because the row had already been processed by csv.reader
.
这篇关于Python解析csv文件 - 用冒号替换逗号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!