如何搜索文本'或者'数字'在带有Python的csv文件中,如果存在,则只将第一列和第二列值打印到新的csv文件

时间:2017-05-15 18:07:47

标签: python python-2.7 csv

我想使用Python执行以下操作。

Step-1: Read a specific third column on a csv file using Python.
Step-2: Create a list with values got from step-1
Step-3: Take the value of index[0], search in csv file, if present print the values of column 1 and 2 only to a new csv file(There are 6 columns). If Not presents just ignore and goto next search.

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,5,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,

为此编写的Python脚本:

import csv
import time
from collections import defaultdict

columns = defaultdict(list)

with open('file1.csv') as f:
    reader = csv.reader(f)
    reader.next()
    for row in reader:
        for (i,v) in enumerate(row):
            columns[i].append(v)
#print(columns[2])

b=(columns[2])
for x in b[:]:
    time.sleep(1)
    print x

以上脚本的输出:

MacBook-Pro:test_usr$ python csv_file.py 
1
1
2
3
5
6
7
8
8
MacBook-Pro:test_usr$

我可以执行第1步和第2步。

请指导我做第3步。那就是如何在csv文件中搜索文本/字符串,以及如何提供如何仅将特定列值提取到新的csv文件?

输出文件应如下所示:

a,ab
b,cd
c,ef
d,gh
e,ij
f,kl
g,mn
h,op
i,qr

注意:搜索字符串将来自另一个csv文件。请不要直接回答第1列和第2列打印值的直接答案。

FINAL CODE看起来像这样:

import csv
import time
from collections import defaultdict

columns = defaultdict(list)

with open('file1.csv') as f:
    reader = csv.reader(f)
    reader.next()
    for row in reader:
        for (i,v) in enumerate(row):
            columns[i].append(v)
            b=(columns[2])

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

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,5,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,

file2.csv:

count,name,number,Type,status,Config Version,,IP1,port
1,bob,1,TRAFFIC,end,1.2,,1.1.1.1,1
2,john,1,TRAFFIC,end,2.1,,1.1.1.2,2
4,foo,2,TRAFFIC,end,1.1,,1.1.1.3,3
5.333333333,test,3,TRAFFIC,end,3.1,,1.1.1.4,4
6.833333333,raa,5,TRAFFIC,end,5.1,,1.1.1.5,5
8.333333333,kaa,6,TRAFFIC,end,7.1,,1.1.1.6,6
9.833333333,thaa,7,TRAFFIC,end,9.1,,1.1.1.7,7
11.33333333,paa,8,TRAFFIC,end,11.1,,1.1.1.8,8
12.83333333,maa,8,TRAFFIC,end,13.1,,1.1.1.9,9

如果我运行上面的脚本,输出file3.csv:

1,bob
2,john
1,bob
2,john
1,bob
2,john
1,bob
2,john
1,bob
2,john
1,bob
2,john
1,bob
2,john
1,bob
2,john
1,bob
2,john
1,bob
2,john
1,bob
2,john
1,bob
2,john
.
.
.

Its goes like this in loop

但输出应该是这样的:

count,name
1,bob,
2,john,
4,foo,
5.333333333,test,
6.833333333,raa,
8.333333333,kaa,
9.833333333,thaa,
11.33333333,paa,
12.83333333,maa,

2 个答案:

答案 0 :(得分:2)

我认为你应该重新考虑你的方法。您只需迭代CSV文件即可实现目标,而无需创建中间dictlist ...,并且由于您希望使用特定列,因此您可以制作使用DictReaderDictWriter

,生活更轻松,代码更具可读性
import csv
import time

search_string = "whatever"

with open('file1.csv', 'rb') as f, open('file2.csv', 'wb') as g:
    reader = csv.DictReader(f)
    c1, c2, c3, *_ = reader.fieldnames
    writer = csv.DictWriter(g, fieldnames=(c1, c2))
    for row in reader:
        if row[c3] == search_string:
            writer.writerow({c1:row[c1], c2:row[c2]})

请注意,csv模块将始终返回字符串。如果您需要,您必须自己处理数据类型转换(我已经将其留在上面)。

如果您不想使用DictReader / DictWriter,我认为它有点冗长,并且不希望输出文件中有标题:

with open('file1.csv') as f, open('file2.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 :(得分:2)

  

这是如何在csv文件中搜索文本/字符串,如果存在,如何   仅将特定列值提取到新的csv文件?

这是两个问题。

第一个问题:要搜索文件中的文本,最简单的答案是将文件文本读入内存并查找文本。如果您想在正在阅读的csv的特定列中查找文本,可以使用DictReader简化生活:

for row in reader:
  if search_target in row[header]:
    # found it!

第二个问题: 将特定列写入新csv的一种方法如下:

keys = ["Country", "Location"]
new_rows = [{key: row[key] for key in keys} for row in reader]
writer = csv.DictWriter(somefile, keys)
writer.writerows(new_rows)