python 读取csv 替换,Python解析csv文件 - 用冒号替换逗号

该博客讲述了如何用纯Python代码替换CSV文件中的逗号为冒号,而不是使用内置的csv模块。作者遇到的问题是尝试遍历并修改csv.reader返回的行,但发现这样做无效,因为行已经被处理过。解决方案是直接设置csv.writer的分隔符为冒号,然后使用writer.writerows()方法写入修改后的行。
摘要由CSDN通过智能技术生成

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.

解决方案

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)

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值