building 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: building class (/thread-24837.html) |
building class - zarize - Mar-06-2020 Hey guys, I wanted to develop my coding so i am about to learn OOP. I want to build class which will: 1) read excel file in the folder 2)transfer it into dataframe I was able to do: class df_excel: def __init__(self, filename, sheetname): self.file = filename self.sheetname = sheetname def excel_to_df(self): self.create_df = pd.read_excel(self.file, self.sheetname) return self.create_df A = df_excel(r'C:\Users\user\test.xlsx', 'Database_sheet') df = A.excel_to_df() print(df)But i would like to skip providing filename, and make it automatized with function: def get_names(self): cwd = os.getcwd() for file in os.listdir(cwd): if file.endswith('.xlsx'): filename = cwd + '\\' + file return filenamei am confused how to combine it into 1 class... Please help :( RE: building class - Larz60+ - Mar-07-2020 I can't test the following as I don't have a bunch of xlsx files lying around if you get errors that you can't figure out, post them from pathlib import Path import os class df_excel: def __init__(self, sheetname): # set starting path (src code repository) os.chdir(os.path.abspath(os.path.dirname(__file__))) homepath = Path('.') self.filelist = [filename for filename in homepath.iterdir() \ if filename.is_file() and filename.suffix == '.xlsx'] self.sheetname = sheetname def excel_to_df(self): for file in self.filelist: self.create_df = pd.read_excel(file, self.sheetname) yield self.create_df def main(): A = df_excel(r'Database_sheet') for df in A.excel_to_df() print(df) if __name__ == '__main__': main() RE: building class - zarize - Mar-09-2020 Thank you Larz60+ :) yield was missing puzzle in my case :P i tried some different ways to do it on my own and i was trying with return instead of yield class df_excel: cwd = os.getcwd() def __init__(self, sheetname): self.sheetname = sheetname def excel_to_df(self): cwd = os.getcwd() for file in os.listdir(cwd): if file.endswith('.xlsx'): filename = cwd + '\\' + file self.create_df = pd.read_excel(file, self.sheetname) yield self.create_df def main(): A = df_excel('Prices') for df in A.excel_to_df(): print(df) main() RE: building class - Larz60+ - Mar-09-2020 Can't do much without seeing the full, unaltered error trace. (in error tags) Please post. RE: building class - zarize - Mar-10-2020 (Mar-09-2020, 07:21 PM)Larz60+ Wrote: Can't do much without seeing the full, unaltered error trace. (in error tags) everything is fine, topic is solved! :P your previous response was enough to solve it :) Thank you! |