简体   繁体   中英

Python 3.x - Searching a CSV file for a specific value then printing the row

My task is to read a csv file, find the largest value in the third column and then store the row(s) with that largest value.

So far, I have been able to read the csv file and find the largest value but I am unable to search for that value and get the rows.

import csv

with open('file_name.csv', 'r', newline='') as f:
    reader = csv.DictReader(f)
    ThirdCol = []

#This block takes the 3rd column in the file and makes it a list. After sorting, the last value is the "largest" value.
    for col in reader:
        ThirdCol.append(col['colName']) 
        ThirdCol.sort()
        Largest = ThirdCol[-1]

#This block attempts to take the found largest value and print rows with their third columns matching the largest value.
    for row in reader:
        if Largest == row[2]:
            print (row)

I'm not sure what is wrong here, my notebook is giving no output or error messages. I've narrowed down the issue to the "row" section of my code. My intent is to search through the [2] element in the rows, which should be the third column, and print the rows that have a row[2] matching what I determined to be the largest value in the previous for loop.

From other questions on stackoverflow, I'm also thinking my problem may be related to the use of "DictReader" and how in the first for loop I'm searching using strings and the second for loop I'm using an integer.

I'm very new to python, and programming in general. I was only given the link to the documentation for CSV and we have only covered the basic data types, functions and loops. I appreciate any direction anyone can give me, thanks.

import csv

with open('file_name.csv', 'r', newline='') as f:
    reader = csv.reader(f)
    # Saving CSV data into a list
    data = [x for x in reader]

# Get maximum value from list using max(list) function
max_thirdcol_val = max([x[2] for x in data])

# Check row by row for 3 col value to max with Max value
for row in data:
    if row[2] == max_thircol_val:
        print(row)

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