如何在csv文档中找到特定的行在python [英] How to find specific rows in csv document in python

查看:1189
本文介绍了如何在csv文档中找到特定的行在python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要做的是读入一个csv文档,并找到SN列> 20中的所有值,并创建一个只有SN> 20的行的新文件。

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.

我知道我需要:


  1. 读取原始档案

  2. 打开一个新文件

  3. 迭代原始文件的行

能够做的是找到值为SN> 20的行

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

所以我的问题是, 20并将其转换为新文件?

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

推荐答案

将数据保存在列表中,然后将列表写入文件。 / p>

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 + ",")

这篇关于如何在csv文档中找到特定的行在python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆