python筛选出csv满足某条件的行_如何在csv文档中找到特定的行在python

1586010002-jmsa.png

What I'm trying to do is read into a csv document and find all values in the SN column > 20 and make a new file with only the rows with SN > 20.

I know that I need to do:

Read the original File

Open a new file

Iterate over rows of the original file

What I've been able to do is find the rows that have a value of SN > 20

import csv

import os

os.chdir("C:\Users\Robert\Documents\qwe")

with open("gdweights_feh_robert_cmr.csv",'rb') as f:

reader = csv.reader(f, delimiter= ',')

zerovar = 0

for row in reader:

if zerovar==0:

zerovar = zerovar + 1

else:

sn = row [11]

zerovar = zerovar + 1

x = float(sn)

if x > 20:

print x

So my question is how do I take the rows with SN > 20 and turn it into a new file?

解决方案

Save the data in a list, then write the list to a file.

import csv

import os

os.chdir(r"C:\Users\Robert\Documents\qwe")

output_ary = []

with open("gdweights_feh_robert_cmr.csv",'rb') as f:

reader = csv.reader(f, delimiter= ',')

zerovar = 0

for row in reader:

if zerovar==0:

zerovar = zerovar + 1

else:

sn = row [11]

zerovar = zerovar + 1

x = float(sn)

if x > 20:

print x

output_ary.append(row)

with open("output.csv",'w') as f2:

for row in output_ary:

for item in row:

f2.write(item + ",")

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值