Home > Blockchain >  Trouble opening dataframe with OOP
Trouble opening dataframe with OOP

Time:07-16

I am new at OOP and I am stuck. I am trying to read in an excel file from the user and output the dataframe. My code does not give any errors but it also doesn't output anything. What am I doing wrong here?

class openSheet():
    def openFile(self, filepath):
        #read in the file
        filepath = input("Please enter a valid file path to a xls: ")
        while not os.path.isfile(filepath):
            print("Error: That is not a valid file, try again...")
            filepath = input("Please enter a valid file path to a xls: ")
        
        filepath = openSheet()
        df = pd.read_excel(filepath, skiprows=1)
        return df
df = openSheet()

CodePudding user response:

Try this, since you are taking path as input so don't need to pass it while calling. 'data' is the required output, hope this will help

class openSheet:
    def openFile(self):
        filepath = input("Please enter a valid file path to a xls: ")

        while not os.path.isfile(filepath):
            print("Error: That is not a valid file, try again...")
            filepath = input("Please enter a valid file path to a xls: ")
    
        df = pd.read_excel(filepath, skiprows=1)
        return df

df = openSheet()
data = df.openFile()

CodePudding user response:

this line df = openSheet() only creates an openSheet object, you need to call the openFile() method on that object.

Method: (in OOP) is what we call a function that is defined within a class.

df = openSheet()
returned_df = df.openFile() #since you want to capture the returned dataframe in a variable.

this is just an extention to Abhishek Kumar's answer. Hope this helps.

CodePudding user response:

Make sure you have the correct imports

import os
import pandas as pd

Also you'll have to call the openFile method using the df instance like so:


df.openFile('filename')

  • Related