I am trying to read a CSV file into a list using a class. The method runs correctly from within the file containing the method, but when I try to call the method in main.py using a class I get the following error: Expected type 'Readit', got 'str' instead. Can you help me fix this code so it will run and explain why my code is wrong? TIA.
This is my directory in Pycharm Project->PythonTest->main.py, Stuff.py, test.csv
CSV file contents
test.csv file contents are a,b,c (line 1), 1,2,3 (line 2) and 4,5,6 (line 3)
The class in Stuff.py
class Readit:
def __init__(self, file_name):
self.file_name = file_name
def csv_to_list(self):
from csv import DictReader
with open(self.file_name) as a_file:
csv_reader = DictReader(a_file)
temp = csv_reader
print(temp)
The main.py file
from Stuff import Readit
file_name = "test.csv"
test_result = Readit.csv_to_list(file_name)
print(test_result)
When run in stuff csv_to_list gives this output [{'a': '1', 'b': '2', 'c': '3'}, {'a': '4', 'b': '5', 'c': '6'}]
but I get the error below when I try to call the method in main.py
Expected type 'Readit', got 'str' instead
You sent the file_name to the function instead to the object and your function doesn't return any result. If you change your code a little bit:
import csv
class Readit:
def __init__(self, file_name):
self.file_name = file_name
def csv_to_list(self):
dict_list = []
with open(self.file_name, newline='') as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
dict_list.append(row)
return dict_list
def main():
file_name = "test.csv"
obj = Readit(file_name).csv_to_list()
print(obj)
if __name__ == "__main__":
main()
Output:
[{'a': '1', 'b': '2', 'c': '3'}, {'a': '4', 'b': '5', 'c': '6'}]