Home > Back-end >  Creating a function to open a file while naming it
Creating a function to open a file while naming it

Time:10-12

I am trying to create a function to open several files from a local directory and to name it. I have tried the following (which already works outside of the function):

def read_csv_for_tsv_files(table_name):
{table_name}_scn_csv = pd.read_csv(fr'C:\Users\xxx\Desktop\{table_name}.csv', sep=';',
                                      error_bad_lines=False)

However, I am getting an invalid syntax error. Does anybody have advice?

The line does work like this:

table_name_scn_csv = 
pd.read_csv(r'C:\Users\xxx\Desktop\table_name_scn.csv',sep=';', 
error_bad_lines=False)

CodePudding user response:

It looks like you are trying to assign to a dynamically named variable based on the table name. While it is possible to do this using e.g. globals, it is probably not a good idea.

If you want to store the loaded files so that they are accessible by name, the easiest way is probably to use a dict:

tables = {}

def load_csv(table_name):
    tables[table_name] = pd.read_csv(...)

Then you can access each table using the [] operator on the dict:

load_csv("table_1")
load_csv("table_2")

# ...

table_to_use = tables["table_2"]
# do something with table 2...

CodePudding user response:

You can use

eval(f"{table_name}_scn_csv = pd.read_csv(fr'C:\Users\xxx\Desktop\{table_name}.csv', sep=';', error_bad_lines=False)")
  • Related