Combining Multiple CSV Files into a Single DataFrame using Python's Glob Module

Python

Note that all csv files must contain the same columns for this to work.

 1|  import glob
 2|  
 3|  # 1. Declare directory where csv files are stored
 4|  directory = "../data/folds/*.csv"
 5|  
 6|  # 2. Create empty dataframe
 7|  df = pd.DataFrame()
 8|  
 9|  # 3. Iterate through each csv file in the directory, read it into a
10|  # temporary dataframe and then append this to dataframe to the main
11|  # dataframe
12|  for file in glob.glob(directory):
13|      temp_df = pd.read_csv(file)
14|      df = df.append(temp_df)
Did you find this snippet useful?

Sign up for free to to add this to your code library