Pandas에서 특정 폴더에 저장된 모든 CSV 파일을 한 번에 읽어 오려면 파이썬의 glob 모듈과 Pandas의 read_csv() 메서드를 함께 사용하면 됩니다.
예를 들어, 하나의 디렉터리에 여러 개의 CSV 파일이 들어 있다고 가정해 보겠습니다. 이 파일들을 일일이 열지 않고도 몇 줄의 코드로 자동화할 수 있습니다.
1단계: 파일 경로 설정하기
먼저 CSV 파일이 위치한 폴더 경로를 지정합니다. 여기서는 MyProject 폴더를 기준으로 진행하겠습니다.
path = "C:\\Users\\amit_\\Desktop\\MyProject\\"
2단계: glob으로 CSV 파일 목록 가져오기
glob.glob() 함수를 사용하면 지정한 경로에서 확장자가 .csv인 모든 파일을 손쉽게 찾을 수 있습니다.
filenames = glob.glob(path + "*.csv")
3단계: 반복문으로 모든 파일 읽기
이제 for 반복문을 사용해 파일 목록을 순회하면서 각 CSV 파일을 읽고 출력합니다.
for file in filenames:
# csv 파일 읽기
print("\nReading file = ", file)
print(pd.read_csv(file))
전체 예제 코드
지금까지의 과정을 하나로 합친 완성된 코드는 다음과 같습니다.
import pandas as pd
import glob
# MyProject 폴더에서 csv 파일 가져오기
path = "C:\\Users\\amit_\\Desktop\\MyProject\\"
# 확장자가 .csv인 모든 파일 찾기
filenames = glob.glob(path + "*.csv")
print('File names:', filenames)
# for 반복문으로 모든 csv 파일 순회
for file in filenames:
# csv 파일 읽기
print("\nReading file = ", file)
print(pd.read_csv(file))
실행 결과
위 코드를 실행하면 폴더에 있는 각 CSV 파일의 이름과 데이터가 차례대로 출력됩니다.
Reading file = C:\Users\amit_\Desktop\MyProject\Sales1.csv
Car Place UnitsSold
0 Audi Bangalore 80
1 Porsche Mumbai 110
2 RollsRoyce Pune 100
Reading file = C:\Users\amit_\Desktop\MyProject\Sales2.csv
Car Place UnitsSold
0 BMW Delhi 95
1 Mercedes Hyderabad 80
2 Lamborgini Chandigarh 80
응용: 여러 CSV 파일을 하나의 DataFrame으로 합치기
각 파일을 개별적으로 확인하는 대신 하나의 DataFrame으로 통합하고 싶다면 pd.concat()을 활용하면 됩니다.
import pandas as pd
import glob
path = "C:\\Users\\amit_\\Desktop\\MyProject\\"
filenames = glob.glob(path + "*.csv")
df_list = [pd.read_csv(file) for file in filenames]
combined_df = pd.concat(df_list, ignore_index=True)
print(combined_df)
이렇게 하면 폴더 안의 모든 CSV 데이터가 인덱스가 재정렬된 단일 DataFrame으로 병합되어, 이후 분석 작업을 훨씬 편리하게 진행할 수 있습니다.