[Python/파이썬] CSV 여러 파일 하나로 합치기

코코._.

·

2021. 1. 12. 09:49

728x90




우선 합칠 CSV file을 3개 만들어서 D:/practice/original/ 경로에 저장하였다.

 

 

sample01, sample02, sample03 파일은 각각 아래와 같이 만들었다.

 

 

 

아래의 코드를 사용하여 CSV 파일을 하나로 합쳐보았다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
import csv
import glob
import os
 
input_path = r'D:/practice/original/' #합칠 파일들이 들어있는 디렉토리 경로
output_path = r'D:/practice/sample_merge.csv' #최종 파일명
 
 
 
file_list=glob.glob(input_path+'*.csv')
 
 
with open(output_path,'w'as f:
  for i, file in enumerate (file_list): #첫 번째 파일은 그대로 불러오기
    if i==0#첫 번째 파일은 그대로 불러오기
      with open(file,'r'as f2:
        while True:
          line=f2.readline()
          if not line:
            break
          f.write(line)
      print(file.split('\\')[-1])
 
    else:
      with open(file,'r'as f2:
        n=0
        while True:
          line=f2.readline()
          if n!=0#2번째 파일부터는 첫번째 줄(헤더)제외
            f.write(line)
          if not line:
            break
          n+=1
      print(file.split('\\')[-1])
 
file_num=len(next(os.walk('D:/practice/original/'))[2]) #합친 파일의 총 개수 
print(file_num,' file merge complete...')
 
cs

 

실행 결과

그 결과 아래와 같이 지정된 경로에 3개의 파일이 잘 합쳐진 파일이 생성된 것을 확인할 수 있다.

 

만약 파일의 공통된 행의 개수가 더 많다면 else 부분에

if n!=0 and n!=1 and n!=2

이렇게 합칠 때 제외할 행을 더 써주면 된다.  

 

300x250