简体   繁体   中英

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:

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? Essentially what I want it to do is find 1944, then print the whole row 1944 is in.

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')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM