![](/img/trans.png)
[英]How to search for a 'text' or 'number' in a csv file with Python AND if exists print only first and second column values to a new csv file
[英]How to search for a specific column value in csv file, if present , write first two column values to a new csv file with Python?
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])
但是它只打印最后两行的值。
我看不到您的代码中的任何问题:
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的值...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.