Skip to content
Sign upLog in
← Back to Community

Reading csv files in Python

Profile icon
JacobKubiak

How do you read a csv file in python on repl.it? I've tried uploading the files I'm trying to read and keep getting an error saying that the name of the file is not defined

Voters
Profile icon
UCHECHUKWU1
Profile icon
JacobKubiak
Comments
hotnewtop
Profile icon
LeonDoesCode

I'm looking at this repl, I hope it is the right one (try and include it in future posts).

Problems

One thing is that you have imported the csv library multiple times which can cause problems.

You also used the word sum as your variable, which is one of Pythons defined words.

You should also specify in your open call that it should be read-only as to not break the file.

open(filePath, "r")

Also, with files (unless opened using with), you need to close them.

file.close()

Code

I rewrote what your code to be easier to read. Please note that this is what I thought it should do, maybe not what you intended. This is also only one of the functions you added.

The code is here:

import csv def csv_sum(filePath): with open(filePath, newline='') as f: # Open file as f reader = csv.reader(f) # Create csv reader for f result = 0 for line in reader: # lines in reader list for num in line: # nums in lines result += float(num) # Add num to result print(result) # Print result csv_sum("test.csv") # Run csv_sum with file in same directory, should equal 10.5 csv_sum("files/test2.csv") # Run csv_sum with file in different directory, should equal 130.0
Profile icon
mwilki7

Would you be able to post the link of the repl it is not working with?

Profile icon
wolfonthefritz

@mwilki7

do you know how I can fix my Repl, I am trying to make it so I can pull a certain row and print it?