r/learnpython • u/lolololloloolmemes • 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)
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_valOr 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
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 here1
1
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
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.