0

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)
  • Can you give more detail about what, specifically, works outside of the function? Assigning to a variable without the `{}`? – Phydeaux Oct 11 '21 at 10:25
  • yes, adjusted the question.. – progammerattempt Oct 11 '21 at 10:28
  • What is `{table_name}_scn_csv` meant to be ? –  Oct 11 '21 at 10:32
  • 1
    Does this answer your question? [How do I create variable variables?](https://stackoverflow.com/questions/1373164/how-do-i-create-variable-variables) – buran Oct 11 '21 at 10:42
  • 2
    Creating names dynamically is not good idea, check http://stupidpythonideas.blogspot.com/2013/05/why-you-dont-want-to-dynamically-create.html – buran Oct 11 '21 at 10:47
  • not related to your error - but I've posted a solution for this a while back using pandas and pathlib see [here](https://stackoverflow.com/questions/59823218/creating-and-assigning-different-variables-using-a-for-loop/59823370#59823370) – Umar.H Oct 11 '21 at 11:18

1 Answers1

0

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...
Phydeaux
  • 2,795
  • 3
  • 17
  • 35
  • In what way does this address the question, which is about a syntax error ? –  Oct 11 '21 at 10:35
  • 1
    The syntax error is caused by trying to dynamically name a variable using some f-string-like syntax, presumably in order to reference each table by its name. This answer is what OP should do instead. – Phydeaux Oct 11 '21 at 10:51
  • @YvesDaoust edited for clarity – Phydeaux Oct 11 '21 at 10:55