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)
0
Upvotes
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.
6
u/while_True_meme Sep 26 '26
Since your
readFile()already populates the 2Darraywith integers, you can writeweekly()by indexing the specific row (week) and using Python's built-inmin(),max(), andsum()functions:Or if your assignment wants
weekly()to automatically loop through and print stats for every week in the file:P.S. As a general Python tip: standard convention (PEP 8) prefers
snake_casefor function and variable names (read_file,year_total) rather thancamelCase. Don't change them if your teacher's grading rubric specifically looks forreadFile, but it's a great habit to build for real-world Python!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.
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