BadZipFile: File is not a zip file

신 영·2024년 8월 22일
1

Troubleshooting

목록 보기
1/1
post-thumbnail

❓ 문제

여러 엑셀 파일 병합을 위해 엑셀을 읽을 때 BadZipFile: File is not a zip file 에러 발생.

❗ 원인

사내보안망에서 보안이 걸려있는 엑셀 파일들은 openpyxl이나 xlsxwriter로 엑셀 파일을 읽고 쓸 수 없다고 한다.

💡 해결

xlwings 모듈 사용

xlwings는 엑셀 자동화 모듈로, 엑셀을 제어한다는 점에서 openpyxl과 비슷해보이지만 xlwings는 엑셀의 매크로(VBA : Visiaul Basic for Appliacation)와 파이썬을 연동하는 것이 가능하다.

openpyxl 사용시 (에러 발생했던 코드)

import os
import pandas as pd

# 폴더 경로 지정
folder_path = './data'

# 병합할 모든 DataFrame을 담을 리스트
all_data = []

# 파일 리스트 가져오기
file_list = os.listdir(folder_path)

# 'opx.xls' 형식의 파일들을 필터링하여 데이터 병합
for file_name in file_list:
    if file_name.endswith('.xls'):
        file_path = os.path.join(folder_path, file_name)
        # 각 파일을 읽어서 DataFrame으로 변환
        df = pd.read_excel(file_path, engine = 'openpyxl')
        all_data.append(df)

# 모든 데이터프레임을 하나로 합침
merged_data = pd.concat(all_data, ignore_index=True)

# 병합된 데이터를 새로운 파일로 저장
output_file = os.path.join(folder_path, 'merged_data.xls')
merged_data.to_excel(output_file, index=False)


xlwings 사용시 (에러 해결된 코드)

pip install xlwings
import os
import xlwings as xw
import pandas as pd

# 폴더 경로 지정
folder_path = './data'

# 병합할 모든 DataFrame을 담을 리스트
all_data = []

# 파일 리스트 가져오기
file_list = os.listdir(folder_path)

# 'opx.xls' 형식의 파일들을 필터링하여 데이터 병합
for file_name in file_list:
    if file_name.endswith('.xls'):
        file_path = os.path.join(folder_path, file_name)
        
        # Excel 파일 열기
        with xw.App(visible=False) as app:
            wb = app.books.open(file_path)
            sheet = wb.sheets[0]
            
            # 데이터를 DataFrame으로 변환
            df = sheet.used_range.options(pd.DataFrame, header=1, index=False).value
            all_data.append(df)
            wb.close()

# 모든 데이터프레임을 하나로 합침
merged_data = pd.concat(all_data, ignore_index=True)

# 병합된 데이터를 새로운 파일로 저장
output_file = os.path.join(folder_path, 'merged_data.xlsx')
merged_data.to_excel(output_file, index=False)

참고자료
[PyQt5] 사내 보안망 DRM 피해서 파일 읽기, 불러오기, 수정하기 | zipfile.BadZipFile: File is not a zip file
3-2. Excel - xlwings 소개

0개의 댓글