-1

I have made a piece of code with a menu that allows for a couple different user inputs, but have currently backed myself into a corner.

Below is a sample of the menu:

while True:
    choice = input("""\nChoose option:

    0: Back
    1: Print df_bhole
    2: Print df_soil_descr_ocr

Chosen option: """)

    if choice == '0':
        break
    elif choice == '1':
        printdf('df_bholes.csv',bh_params_dtypes)
    elif choice == '2':
        printdf('df_soil_desc_ocr.csv',soil_desc_ocr_dtypes)

This launches the code printdf which can be seen below.

def printdf (filename,parameters):

try:
    df = pd.read_csv('df_bholes.csv', sep='\t', index_col=0, dtype=bh_params_dtypes)
    print(df)
        except:
            try:
                df=os.path.splitext(filename)[0]
                print(df)
            except:
                print("This dataframe has not yet been created")

The problem I have with this code is that "df", in the event that no .csv file is found, is a string, due to "filename" being one, and as such the print will just be df_bhole or df_soil_descr_ocr.

The output i really want is the entire dataframe saved in the name df_bhole.

I've seen people talk about dictionaries, but it seems that these would require me to hardcode options depending on the input from filename.

Is there an option to simply take 'df_bhole' and turn it into df_bhole?

  • It only prints that the dataframe doesn't exists if there's no .csv file to read data from, and if the dataframe doesn't exist anywhere in the memory of the program. – Christian Emil Johansen Feb 20 '19 at 12:08

1 Answers1

1

Yes. Use eval()

eval('df_bhole')
Ninad Gaikwad
  • 4,272
  • 2
  • 13
  • 23
  • 1
    This answer could be improved by providing an explanation of how this would help and a more complete code example. – scotty3785 Feb 20 '19 at 11:56
  • better use [ast.literal_eval](https://docs.python.org/3.6/library/ast.html) – Nullman Feb 20 '19 at 11:58
  • @ChristianEmilJohansen just be aware of [Why is using 'eval' a bad practice?](https://stackoverflow.com/questions/1832940/why-is-using-eval-a-bad-practice). – keepAlive Feb 20 '19 at 12:21