[英]How do I search for a specific field in a csv file then print the entire row in Python
I would include my whole program but it is too long so I will provide an example:我会包括我的整个程序,但它太长了,所以我将提供一个例子:
Say I had this csv file:假设我有这个 csv 文件:
John, 23, 1944, Africa
Fred, 45, 1922, China
Bob, 23, 1999, Japan
How do I search the file and print the row that 1944 is specifically in?如何搜索文件并打印 1944 所在的行? Essentially what I want it to do is find 1944, then print the whole row 1944 is in.
基本上我想要它做的是找到 1944,然后打印 1944 所在的整行。
Also, if it's structured like另外,如果它的结构像
Name, Age, Year, Nation
John, 23, 1944, Africa
Fred, 45, 1922, China
Bob, 23, 1999, Japan
How would you print the found row plus the top row as well?你将如何打印找到的行加上顶行?
Many thanks.非常感谢。
Edit: Why is down voting necessary?编辑:为什么需要投反对票? I legitimately cannot find any information on this.
我合法地找不到任何关于此的信息。 Therefore I have to ask.
所以我不得不问。
This program answers your first question:该程序回答您的第一个问题:
import csv
import sys
with open('csv1.txt') as fp:
reader = csv.reader(fp, skipinitialspace=True)
writer = csv.writer(sys.stdout)
writer.writerows(row for row in reader if row[2] == '1944')
And this answers your second question:这回答了你的第二个问题:
import csv
import sys
with open('csv2.txt') as fp:
top_row = next(fp)
sys.stdout.write(top_row)
reader = csv.reader(fp, skipinitialspace=True)
writer = csv.writer(sys.stdout)
writer.writerows(row for row in reader if row[2] == '1944')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.