python对csv文件中的数据进行分类_使用python替换csv文件中的数据

1586010002-jmsa.png

This is the new input file format. I need to automate the process of replacing the content of one column in a .csv file with the use of python. I can also open the .csv file using Notepad and replace the content of the column but the file is very huge and it is taking a long time.

Name ID class Num

"kanika",""University ISD_po.log";" University /projects/asd/new/high/sde"","MBA","12"

"Ambika",""University ISD_po.log";" University /projects/asd/new/high/sde"","MS","13"

In the above, I need to replace the content of ID column. ID column is very inconsistent as it has big spaces and symbols like(; , /) in the content.The new content in the ID column should be "input".

This Id column is enclosed with 2 double quotes and has some extra spaces as well. Whereas other columns have only 1 double quote.

Is there any way to do it in python?

解决方案

Read the .csv line-by-line, split on ,, and replace the second column with "input".

Write it out (to a different file) as you go:

f = open('mycsv.csv','rb')

fo = open('out.csv','wb')

# go through each line of the file

for line in f:

bits = line.split(',')

# change second column

bits[1] = '"input"'

# join it back together and write it out

fo.write( ','.join(bits) )

f.close()

fo.close()

Then you can rename it to replace the original file if you like.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值