Home > front end >  Python read data from a file into a class
Python read data from a file into a class

Time:07-05

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 3x3 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.

CodePudding user response:

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())
  • Related