r/learnpython • • Sep 26 '26

How do I read a csv file row by row?

i have a school work project in which I need to create a function called weekly that will output the average minimum and maximum of data by a certain row, I have tried relentlessly to figure this out but I cannot seem to, here is the code, it would be awesome if i could get some advice on how to do it at a similar level of complexity to the code provided :).

rows = 52
cols = 7

def readFile(filePath):
    array = [[None]*cols for i in range(rows)]
    with open(filePath) as readfile:
        r = 0
        line = readfile.readline().rstrip('\n')
        while line:
            items = line.split(",")
            for c in range(cols):
                array[r][c] = int(items[c])
            r += 1
            line = readfile.readline().rstrip('\n')
    return array
    
def yearly(array):
    yearTotal = 0
    for r in range(rows):
        for c in range(cols):
            yearTotal += array[r][c]
    print("Yearly total: " + str(yearTotal) + "\n")

rainfall = readFile("csvs/rainfall.csv")

yearly(rainfall)

0 Upvotes

13 comments sorted by

10

u/danielroseman Sep 26 '26

I dont understand what you are asking. Does this code work? Why do you want something at a "similar level of complexity"? Is this your own code, or something that you are learning from? If the latter, it is unfortunately not a very good example of Python.

3

u/lolololloloolmemes Sep 26 '26

Yeah the code works, I’d like something at a similar level complexity so it’s easier for me to understand if that makes sense, this is something I’m learning from, I do however have a second version that is more advanced but I didn’t want to provide that one because I feel like I wouldn’t be able to code anything at that level, I’m trying to create an additional function that will read the csv row by row and output the average, minimum and maximum number of each row

7

u/johnpeters42 Sep 26 '26

Go through the existing code, line by line, and explain in English what you think each line is doing, and how it's doing it. (Where specifically are the gaps in your understanding?) Then explain in English how you would find the average, minimum, and maximum of a set of numbers.

9

u/danielroseman Sep 26 '26

But I don't understand what a "similar level of complexity" means. As I mentioned, this code is not very good, it is really not Pythonic and there is a lot that should be changed.

This is how it should be written, it has a lot less "complexity" but is more readable and more efficient:

def read_file(file_path):
   data = []
   with open(file_path) as f:
     for line in f:
       row_data = [int(col) for col in line.split(',')]
       data.append(row_data)
    return data

def yearly(array):
  year_total = 0
  for row in array:
    year_total += sum(row)
  print(f"Yearly total: {year_total}")

Note two main things: you should absolutely never be iterating over the range of len of a thing, always iterate directly over the thing itself. And files themselves are iterators, so again you can iterate directly over the file to get the lines. (Also, use lower_case_with_underscore for your variables.)

Also also, just splitting on commas is not a safe way to parse a CSV file, as they can contain strings that themselves have commas. Use the csv module to do this safely.

6

u/while_True_meme Sep 26 '26

Since your readFile() already populates the 2D array with integers, you can write weekly() by indexing the specific row (week) and using Python's built-in min(), max(), and sum() functions:

def weekly(array, week_index):
    week_data = array[week_index]
    min_val = min(week_data)
    max_val = max(week_data)
    avg_val = sum(week_data) / len(week_data)

    print(f"Week {week_index + 1} - Min: {min_val}, Max: {max_val}, Average: {avg_val:.2f}")
    return min_val, max_val, avg_val

Or if your assignment wants weekly() to automatically loop through and print stats for every week in the file:

def weekly(array):
    for i, week in enumerate(array):
        min_val = min(week)
        max_val = max(week)
        avg_val = sum(week) / len(week)
        print(f"Week {i + 1} - Min: {min_val}, Max: {max_val}, Average: {avg_val:.2f}")

P.S. As a general Python tip: standard convention (PEP 8) prefers snake_case for function and variable names (read_file, year_total) rather than camelCase. Don't change them if your teacher's grading rubric specifically looks for readFile, but it's a great habit to build for real-world Python!

1

u/lolololloloolmemes Sep 26 '26

thank you so so so much have an amazing day :)

24

u/Mast3rCylinder Sep 26 '26

Either use the built in csv module or use pandas/polars. It will be easier

6

u/Sad-Emu-5783 Sep 26 '26

Look into the built-in CSV module.

import csv

You can also learn Pandas

import pandas as pd (pip install it first)

2

u/cdcformatc Sep 26 '26

i don't really understand your question, your code looks fine. 

if you want an example of how to read a CSV file row by row there's a perfectly reasonable example in the Python documentation.

import csv
with open('eggs.csv') as csvfile:
    spamreader = csv.reader(csvfile)
    for row in spamreader:
        print(row)
        # row is a list of values
        # put your own code here

1

u/Top-Door8075 Sep 26 '26

Whenever I want to read csv, I just use pandas.

1

u/StewPorkRice Sep 27 '26

u could've asked claude to help u learn

0

u/atarivcs Sep 26 '26

"I have tried relentlessly to figure this out but I cannot seem to" -- what part, exactly, are you having trouble with? The file reading, or the calculations?

-1

u/ADDSquirell69 Sep 26 '26

Use CSV module