컴퓨터/Python

pandas 엑셀파일 xls xlsx 모두 합치기

풍경소리^^ 2020. 3. 5. 19:05

pip install pandas, xlrd, xlwt

 

 

import os
import glob
import pandas as pd
import numpy as np

# location = os.getcwd()
path_hometax = r'C:\Users\유저이름\hometax\\'

file = path_hometax + '통합.xls'

if os.path.isfile(file):
os.remove(file)

excels = glob.glob(path_hometax + '*.xls*')
exl_list = []
for excel in excels:
if excel == '통합.xls':
continue
# print(excel)
exl_list.append(excel)
print(exl_list)

if len(exl_list) != 0:
df1 = pd.read_excel(exl_list[0], skiprows=5) # 첫번째 파일 이름
cnt = df1.shape[0] # 첫번째 파일 shape[0] 행 갯수 shape[1] 열 갯수
# df1.loc[cnt + 1] = np.nan # 데이터 끝 다음 줄에 nan 데이터
if len(exl_list) == 1:
df_total = df1
else:
for item in exl_list[1:]: # 두번째 파일 부터
df2 = pd.read_excel(item, skiprows=5) # 두번째 파일 이름
cnt = df2.shape[0] # 두번째 파일 shape[0] 행 갯수 shape[1] 열 갯수
# df2.loc[cnt + 1] = np.nan # 데이터 끝 다음 줄에 nan 데이터

df_total = pd.concat([df1,df2], axis=0)
df1 = df_total
df_total.to_excel(path_hometax + '통합.xls', index = False, sheet_name='통합')
else:
print('통합할 파일이 없습니다.')

import pandas as pd
import numpy as np
import os
import glob

location = os.getcwd()
excels = glob.glob('*.xls*')

excel_list = []
for excel in excels:
    if excel == "통합.xlsx":
        continue
    excel_list.append(excel)
    
if len(excel_list) !=0:
    df_total = pd.read_excel(excel_list[0])
    cnt = df_total.shape[0] # 행
#     df_total.loc[cnt+1] = np.nan
    for item in excel_list[1:]:
        df = pd.read_excel(item)
        cnt = df.shape[0] # 행
#         df.loc[cnt+1] = np.nan
        
        df_total = pd.concat([df_total, df2], axis=0)
#         df1 =df_total
    
    df_total.to_excel(location + "/통합.xlsx", index=False, sheet_name="통합")

else:
    print("통합할 파일이 없습니다.")