Python Forum

Full Version: building class
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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 filename
i am confused how to combine it into 1 class... Please help :(
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()
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()
Can't do much without seeing the full, unaltered error trace. (in error tags)
Please post.
(Mar-09-2020, 07:21 PM)Larz60+ Wrote: [ -> ]Can't do much without seeing the full, unaltered error trace. (in error tags)
Please post.

everything is fine, topic is solved! :P your previous response was enough to solve it :) Thank you!