如何在csv文件中搜索特定的列值(如果存在),使用Python将前两个列值写入新的csv文件?

时间:2017-05-16 08:49:57

标签: python python-2.7

file1.csv:

Country,Location,number,letter,name,pup-name,null
a,ab,1,qw,abcd,test1,3
b,cd,1,df,efgh,test2,4
c,ef,2,er,fgh,test3,5
d,gh,3,sd,sds,test4,
e,ij,DDDD,we,sdrt,test5,
f,kl,6,sc,asdf,test6,
g,mn,7,df,xcxc,test7,
h,op,8,gb,eretet,test8,
i,qr,8,df,hjjh,test9,

我想在上面的csv文件的第3列中搜索字符串/数字。如果存在,请写下前两列值'到另一个文件。

例如:

In 3rd column, number 6 is present --- > Then I want write 'f','kl' into a new csv file (with headers) 
In 3rd column, string DDDD is present ---> Then I want to write 'e','ij' into a new csv file.

请指导我们如何使用Python做到这一点?

我正在尝试下面的代码:

import csv
import time

search_string = "1"

with open('file1.csv') as f, open('file3.csv', 'w') as g:
    reader = csv.reader(f)
    next(reader, None) # discard the header
    writer = csv.writer(g)
    for row in reader:
        if row[2] == search_string:
            writer.writerow(row[:2])  

但它的打印只持续两行值。

1 个答案:

答案 0 :(得分:0)

我的代码中没有任何问题:

  • row[2]中行的第三列,您是对的。
  • 前两列是row[0:2]row[:2],你是对的。

如果我模拟阅读,就像这样:

import io
import csv

data = """Country,Location,number,letter,name,pup-name,null
a,ab,1,qw,abcd,test1,3
b,cd,1,df,efgh,test2,4
c,ef,2,er,fgh,test3,5
d,gh,3,sd,sds,test4,
e,ij,DDDD,we,sdrt,test5,
f,kl,6,sc,asdf,test6,
g,mn,7,df,xcxc,test7,
h,op,8,gb,eretet,test8,
i,qr,8,df,hjjh,test9,
"""

with io.StringIO(data) as f:
    reader = csv.reader(f)
    next(reader, None)  # discard the header
    for row in reader:
        if row[2] == "1":
            print(row[:2])

打印:

['a', 'ab']
['b', 'cd']

更改 search_string ...

的值