2

I have a folder that includes folders and these folders include many csv files. I want to import and concatenate all of them in Python.

Let's say main folder: /main

subfolders: /main/main_1

csv: /main/main_1/first.csv

path='/main'
df_list = [] 
for file in os.listdir(path): 
    df = pd.read_csv(file) 
    df_list.append(df) 

final_df = df.append(df for df in df_list) 
2
  • 1
    Can you be more specific. We know what you want to do, but what have you tried, what happened, and what do you not understand? We will not write your code for you Commented Jun 17, 2022 at 18:43
  • [Errno 2] No such file or directory: 'main_1' error occurs. I thought there should be a more practical way for it. Commented Jun 17, 2022 at 18:45

3 Answers 3

2

What about this:

import pandas as pd
from pathlib import Path

directory = "path/to/root_dir"

# Read each CSV file in dir "path/to/root_dir"
dfs = []
for file in Path(directory).glob("**/*.csv"):
    dfs.append(pd.read_csv(file))

# Put the dataframes to a single dataframe
df = pd.concat(dfs)

Change the path/to/root_dir to where ever your CSV files are.

Sign up to request clarification or add additional context in comments.

Comments

1

I found a way to concat all of them but it doesn't satisfy to me as it takes too much time due to computational complexity.

path = "/main"

folders = []
directory = os.path.join(path)
for root,dirs,files in os.walk(directory):
    folders.append(root)

del folders[0]


final = []
for folder in folders:
    df = pd.concat(map(pd.read_csv, glob.glob(os.path.join(folder + "/*.csv"))))
    final.append(df)

Comments

0

Remember to add back main to the path:

df =pd.read_csv(path + "/" + file)

2 Comments

PermissionError: [Errno 13] Permission denied: 'main/main_1' occurs. I guess, we just reach the subfolder for now. I will try to import and concat all csv files from the subfolders now.
You should use 2 nested loops, one to loop through the folders and one to loop through files. You can't open a folder as a file

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.