Home > database >  generator expression to read multiple csv files
generator expression to read multiple csv files

Time:01-25

I can load multiple csv files into multiple pandas dataframes i.e. a, b and c as shown below. However since a, b and c are part of a list, how can I use the item_list list to get items (i.e. a, b and c) instead of manually typing them?

item_list = ['a', 'b', 'c']
file_list = [x   '.csv' for x in item_list]

a, b, c = (pd.read_csv(f) for f in file_list)

However if I do something like below, the three csv files are stored as list of dataframes.

item_list = (pd.read_csv(f) for f in file_list)  
list(item_list)

Result:

[  name
 0    a
 1    a
 2    a,
   name
 0    b
 1    b
 2    b,
   name
 0    c
 1    c
 2    c]

I simply want the dataframes to be stored in respective a, b and c dataframes without the need to type them explicitly. Imagine the situation when the list is large and not just three (i.e. a, b and c) in example shown above.

CodePudding user response:

You can use a list comprehension.

item_list = [pd.read_csv(f) for f in file_list]
  •  Tags:  
  • Related