Reading csv files in Python
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
I'm looking at this repl, I hope it is the right one (try and include it in future posts).
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.
Also, with files (unless opened using
with), you need to close them.
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