0

I have folder which includes many csv files namely a_1, a_2, b_1, b_2, b_1, b_2....

I want to import each csv file as their names. For example

a_1 = pd.read_csv("a_1.csv")

a_2 = pd.read_csv("a_2.csv")

In order to do that:

path = r"C:\Users\Desktop\sync\work\all_csvs"
csv_files = glob.glob(path + "/*.csv")

colname=['time', 'var_1', 'var_2', 'var_3', 'var_4', 'var_5'] 
os.path.basename(csv_files[0]).split(".")[0] = pd.read_csv(csv_files[0], names=colname ,header=None)

But it doesn't work. Is there any way to make the system dynamic? I will use it in the for loop.

Thanks in advance

helloworld
  • 89
  • 1
  • 9
  • Your question isn't very clear: How should your expected output exactly look like? – Timus Aug 06 '22 at 21:14
  • a_1 = pd.read_csv("a_1.csv"), a_2 = pd.read_csv("a_2.csv"), etc – helloworld Aug 06 '22 at 21:16
  • So you want a variable for each dataframe that is named like the corresponding file? That doesn't sound like a good idea. Better do something like in the answer (collect the dataframes in a dictionary with the filenames as keys). (If you really want to do it, then use something like `globals()[filename] = pd.read_csv(filename)` in a loop over the `glob` results - but that's not a good idea.) – Timus Aug 06 '22 at 21:21
  • No, that's not a good idea, use a dictionary. – mozway Aug 06 '22 at 22:06

1 Answers1

1

Once you have the list of files in csv_files, loop through the list to import all of the files.

files = {}

for file in csv_files:
    files[file] = pd.read_csv(os.path.join(path, file), ....)

We use os.path.join to generate the absolute path for the file.

This will store all the imported csv files into the files dictionary with keys as the name of the file.