Home > Software design >  Python If Statement and Lists
Python If Statement and Lists

Time:09-09

i'm fairly new to python and am looking for some help. What i would like to do is read a csv file and then use a for loop with an if statement to locate at rows of that data contain a value and print it out with a header and some formatting using f'.

The issue i seem to have it when finding the data using the if statement, im unsure what i can output the data to, which will then enable it to be printed out (the search output could contain multiple rows and columns):

with open(r'data.csv', 'r') as csv_file:
    # loop through the csv file using for loop
    for row in csv_file:
        # search each row of data for the input from the user
        if panel_number in row:
            ??

CodePudding user response:

Use the csv module. Then in your if statement you can append the row to a list of matches

import csv

matched_rows = []
with open(r'data.csv', 'r') as file:
    file.readline() # skip over header line -- remove this if there's no header
    csv_file = csv.reader(file)
    for row in csv_file:
        # search each row of data for the input from the user
        if row[0] == panel_number:
            matched_rows.append(row)

print(matched_rows)
  • Related