Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python read data from a file into a class

I have a filename ‘my_data_file.csv’ that is a comma separated file of 3 rows and 3 columns with random numbers. I want to read the data and store it into a class ‘MYDATA’. Then I want to print the 3×3 array in the window by typing: class.function(‘my_file.csv’). This is my attempt:

class MYDATA:
    def __init__(self,filename):
        self.filename = filename
        
        # get the main axis of the file.
        self.values = self.get_values_from_file()
      
    def get_values_from_file(self):
        values = []
        with open(filename, 'r') as file:
            for line in file:
                pos = list(map(float, line.split(',')))
                values.append(pos)
        return values

print(MYDATA.get_values_from_file('my_data_file.csv'))

This gives me NameError: name 'filename' is not defined. What do I do wrong? How can I print the values to the screen? I do not want to define a classmethod.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You need to refer filename with self object. Also classname can only access class members, so self.filename wouldn’t have worked.

class MYDATA:
    def __init__(self,filename):
        self.filename = filename
        
        # get the main axis of the file.
        self.values = self.get_values_from_file()
      
    def get_values_from_file(self):
        values = []
        with open(self.filename, 'r') as file:
            for line in file:
                pos = list(map(float, line.split(',')))
                values.append(pos)
        return values

mydataobj = MYDATA(r'my_data_file.csv')
print(mydataobj .get_values_from_file())
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading