Python Forum
Class for reading a csv FIie
Thread Rating:
  • 1 Vote(s) - 2 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Class for reading a csv FIie
#1
Hey,
i have a problem with a homework for university. We have to write a class which can use attributes and read a cs. file. I am on it for several days and dont get a right answer :(
As example i get a csv file like 

Time | Temperature

-------------------------
0.0  | 15.2
3.0  | 16.1
6.0  | 14.8
9.0  | 20.2
Than it should "return" an object with type "table" like this:
(["Time", "Temperature"], [[0.0, 3.0, 6.0, 9.0], [15.2, 16.1, 14.8, 20.2]])
We have to create an attribute "titles" and "cols", Method "__str__(self)" to output the attributes. Mehod "__eq__(self, other)" which returns true if both attributes are equal. Method "parse_csv(self, filename), which reads the given csv file and returns the data as an object, where we have to use csv modul, and the constructor which gets the attributes or the filename and no attributes.
Also they compare it to manual entered data, but you will see it in the code i will paste.
Here is my code so far, that doesnt really work:


import csv

class Table:
    def __init__(self, titles=None, cols=None, filename = None):
        if filename is None:
            self.titles = titles
            self.cols = cols
            self.filename = None
        else:
            self.filename = filename
            self.parse_csv(filename)
    
    def __str__(self):
        return (str(self.titles) +', '+ str(self.cols))
        
    def __eq__(self, other):
        if self.filename == None:
            return (self.titles, self.cols) == (other.titles, other.cols)
        else:
            return self.parse_csv(self.filename) == other
                    
    def parse_csv(self, filename):
        with open(filename) as f:
            reader = csv.reader(f)
            header = next(reader)
            cols = zip(*reader)
        return [header, cols]
and i check it with this, given in the homework:
my_table1 = Table(["title1", "title2"], [["l1"], ["l2"]])

print(my_table1)

assert my_table1.titles[0] == "title1"
assert my_table1.titles[1] == "title2"
assert my_table1.cols[0] == ["l1"]
assert my_table1.cols[1] == ["l2"]

my_table2 = Table(["title1", "title2"], [["l1"], ["l2"]])
assert my_table2 == my_table1


titles = ["Time", "Temperature"]
filename1 = "simple_example.csv"
my_table3 = Table(titles, [[0.0, 3.0, 6.0, 9.0], [15.2, 16.1, 14.8, 20.2]])
my_table3_parsed = Table(filename = "simple_example.csv")

assert my_table3_parsed == my_table3
This is the output with the error:


['title1', 'title2'], [['l1'], ['l2']]



---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-40-82adc121b91e> in <module>()
    20 my_table3_parsed = Table(filename = "simple_example.csv")
    21
---> 22 assert my_table3_parsed == my_table3 # Teilpunkte, falls immerhin dies funktioniert
    23
    24 # dritter Test

<ipython-input-39-dad6bc1a92db> in __eq__(self, other)
    18             return (self.titles, self.cols) == (other.titles, other.cols)
    19         else:
---> 20             return self.parse_csv(self.filename) == other
    21
    22     def parse_csv(self, filename):

<ipython-input-39-dad6bc1a92db> in __eq__(self, other)
    16     def __eq__(self, other):
    17         if self.filename == None:
---> 18             return (self.titles, self.cols) == (other.titles, other.cols)
    19         else:
    20             return self.parse_csv(self.filename) == other

AttributeError: 'list' object has no attribute 'titles'
Reply
#2
As far as I can tell, if you create the Table from a file, there won't be a titles attribute.

As always, when your code doesn't behave as you expect, it is usually because variables don't hold what you expect, add a few print() at the right places to show the contents of variables, and where they aren't what you expect, check where they are produced and add more print() to check the code flow and variable contents.
Unless noted otherwise, code in my posts should be understood as "coding suggestions", and its use may require more neurones than the two necessary for Ctrl-C/Ctrl-V.
Your one-stop place for all your GIMP needs: gimp-forum.net
Reply
#3
I have no something nearly working:
import csv
 
class Table:
    def __init__(self, titles=None, cols=None, filename = None):
            if filename is None:
                self.titles = titles
                self.cols = cols
                self.filename = filename
            else:
                self.file1 = self.parse_csv(filename)
    
    def __str__(self):
            return (str(self.titles) +', '+ str(self.cols))

       
    def __eq__(self, other):
            return (self.titles, self.cols) == (other.titles, other.cols)

                   
    def parse_csv(self, filename):
        with open(filename) as f:
            reader = csv.reader(f)
            self.titles = next(reader)
            self.cols = list(zip(*reader))
            return [self.titles, self.cols]
The only thin ist, that the output from the read file is like 
['Time', 'Temperature'], [('0.0', '3.0', '6.0', '9.0'), ('15.2', '16.1', '14.8', '20.2')]

and schould be like 
['Time', 'Temperature'], [[0.0, 3.0, 6.0, 9.0], [15.2, 16.1, 14.8, 20.2]]

How can i convert it from strings to floats?
Reply
#4
Something like:
cols[0]=[float(x) for x in cols[0]]
but if the syntax of the CSV file is correct, and if you read it properly, you have have gotten floats directly.
Unless noted otherwise, code in my posts should be understood as "coding suggestions", and its use may require more neurones than the two necessary for Ctrl-C/Ctrl-V.
Your one-stop place for all your GIMP needs: gimp-forum.net
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020