我正在尝试从特定目录中的文件夹中读取 .xlsx 文件,并将它们写入/导出到 4 个新的 .xlsx 文件中,每个新的 .xlsx 将包含每年的数据目录。 当我几个月前尝试时,该脚本运行良好,但现在不再运行了。它继续产生 BadZipFile: File is not a zip file 错误。
我错过了什么吗?我尝试过升级和降级 anaconda、python、openpyxl 和 pandas 版本,但没有帮助。
from openpyxl import load_workbook
import pandas as pd
import os
import re
path_folder = r'C:\\Users\\lala\\Downloads\\New folder\\Data Klimatologi\\'
folder_tahun = os.listdir(path_folder)
year_folder
for x in year_folder:
year_folder = os.listdir(path_folder + x)
frames = []
for y in station_folder:
path_file = path_folder + '{}\\{}'.format(x,y)
files = os.listdir(path_file)
for z in files:
pattern = path_folder + '{}\\{}\\{}'.format(x,y,z)
wb = load_workbook(filename = pattern)
sheet = wb.active#has 1 sheet
max_row_for_Tn = max((b.row for b in sheet['B'] if b.value is not None))
cell = 'A9:K%d' % (max_row_for_Tn)
data = sheet[cell]
row_list = []
for row in data:
cols = []
for col in row:
cols.append(col.value)
row_list.append(cols)
df = pd.DataFrame(data = row_list[1:], index=None, columns=row_list[0])
cell_id = sheet.cell(row = 1, column = 3)
pk = cell_id.value
pk = re.sub('[\s]+', '', pk)
pk = int(re.sub(r'[^.,a-zA-Z0-9 \n\.]','', pk))
df['Id WMO'] = pk
frames.append(df)
result = pd.concat(frames)
result.to_excel(r'C:\Users\lala\OneDrive\Documents\Dataset\Dataset Stasiun BMKG Tahun {}.xlsx'.format(x), index = False)
该脚本运行良好,直到
year_folder
给出输出 ('2000','2001','2002','2003','2004')。
这是回溯。
---------------------------------------------------------------------------
BadZipFile Traceback (most recent call last)
<ipython-input-4-e8e2d94d1368> in <module>
7 for z in files:
8 pattern = path_folder + '{}\\{}\\{}'.format(x,y,z)
----> 9 wb = load_workbook(filename = pattern)
10 sheet = wb.active#has 1 sheet
11 max_row_for_Tn = max((b.row for b in sheet['B'] if b.value is not None))
~\anaconda3\envs\Pandas\lib\site-packages\openpyxl\reader\excel.py in load_workbook(filename, read_only, keep_vba, data_only, keep_links)
312 """
313 reader = ExcelReader(filename, read_only, keep_vba,
--> 314 data_only, keep_links)
315 reader.read()
316 return reader.wb
~\anaconda3\envs\Pandas\lib\site-packages\openpyxl\reader\excel.py in __init__(self, fn, read_only, keep_vba, data_only, keep_links)
122 def __init__(self, fn, read_only=False, keep_vba=KEEP_VBA,
123 data_only=False, keep_links=True):
--> 124 self.archive = _validate_archive(fn)
125 self.valid_files = self.archive.namelist()
126 self.read_only = read_only
~\anaconda3\envs\Pandas\lib\site-packages\openpyxl\reader\excel.py in _validate_archive(filename)
94 raise InvalidFileException(msg)
95
---> 96 archive = ZipFile(filename, 'r')
97 return archive
98
~\anaconda3\envs\Pandas\lib\zipfile.py in __init__(self, file, mode, compression, allowZip64)
1129 try:
1130 if mode == 'r':
-> 1131 self._RealGetContents()
1132 elif mode in ('w', 'x'):
1133 # set the modified flag so central directory gets written
~\anaconda3\envs\Pandas\lib\zipfile.py in _RealGetContents(self)
1196 raise BadZipFile("File is not a zip file")
1197 if not endrec:
-> 1198 raise BadZipFile("File is not a zip file")
1199 if self.debug > 1:
1200 print(endrec)
BadZipFile: File is not a zip file
错误信息完全正确。当前版本的 Excel 使用
.xlsx
格式,这是包含小目录树的 zip 文件。该格式直到 Excel 2007 才引入。假设这些文件确实来自 2001 年、2002 年等,它们采用旧式 Excel .xls
格式,不是 zip 文件。 pandas
不知道如何导入 .xls
文件。您可能需要找到一个单独的模块来转换它们。
结果发现其中一个
.xlsx
文件被重复了。我删除了重复的文件,错误不再出现。
如果有人发现相同的错误,您可以单独检查它们是否在您的目录中存在损坏/重复的文件。
只要文件中包含不同的值,使用相同的文件名就不会出现问题。