![]() |
How to read file inside class - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: How to read file inside class (/thread-26450.html) Pages:
1
2
|
RE: How to read file inside class - buran - May-02-2020 self in the class is the instance itself. If you want to use a instance attribute inside the class you need to use it with self.class PythonTraining(): def read_data(self, filepath): base_path = "D:\Data" full_filepath = os.path.join(base_path, filepath, "outsummary2.csv") self.data = pd.read_csv(full_filepath) def cal_rowmean(self, v1): self.xmean = self.data['s3'].mean() + v1 print(self.xmean)Note, that read_data doesn't need to return self.data. Also, note that you need to call read_data() before you call cal_rowmean or you will get AttributeError. It may be better if you refactor your class and move what reading data in class __init__ method (you don't have defined one now) RE: How to read file inside class - snippsat - May-02-2020 You lose flexibility and most of the point of this if hardcore most of the stuff inside the class. It's no so easy with Pandas as often need flexibility to change a lot of stuff(also when read in files). Here a demo,where take stuff in from outside of the class. The can continue in normal way to work with df DataFrame object.
import pandas as pd import os class PythonTraining(): def __init__(self, base_path, file_name): self.base_path = base_path self.file_name = file_name def read_data(self, sep=';', header='infer'): full_filepath = os.path.join(self.base_path, self.file_name) self.data = pd.read_csv(full_filepath, sep=sep, header=header) if __name__ == '__main__': # Now from outside give path and filename base_path = r'E:\div_code\home' file_name = 'movies.csv' df = PythonTraining(base_path, file_name) # Give paramater to csv read sep = ';' #header = None df.read_data(sep) df = df.dataAs you use Spyder here a Screenshot,see that i can continue to work with df object in IPython console.![]() |