【发布时间】:2017-12-15 19:49:43
【问题描述】:
我有一个装满 Excel 文件的文件夹。一个令人讨厌的方面是它们都是.xls(而不是.xlsx)。
我需要做的是读取每个 .xls 文件,删除前 7 行,然后取出剩余的文档并将其添加到“master.xlsx”文件中。 (注意:master.xlsx 不必是预先存在的,可以新建)
我还没有开始尝试删除行,只是尝试简单地合并它们,但不知道如何。我是否需要先以某种方式将所有 .xls 转换为 .xlsx,然后尝试合并?我花了几个小时查看其他 Stack Overflow 问题和在线资源。这似乎是某种古老的技术。另外,值得一提的是我使用的是 Python3。
到目前为止,这是我的代码:
import os
from numpy import genfromtxt
import re
import urllib.request
import pandas as pd
# script directory
script_dir = os.path.dirname(r'C:/Users/Kenny/Desktop/pythonReports/')
# get array list of files
files = []
file_abs_path = script_dir + '/excels/'
for file in os.listdir(file_abs_path):
if file.endswith('.xls'):
excel_file_path = script_dir + '/excels/' + file
files.append(excel_file_path)
# f is full file path
df_array = []
writer = pd.ExcelWriter('master.xlsx')
for f in files:
sheet = pd.read_html(f)
for n, df in enumerate(sheet):
df_array.append(df)
# df = df.append(df)
# df.to_excel(writer,'sheet%s' % n)
print(df_array)
for df in df_array:
# new_df = new_df.append(df)
new_df = pd.concat(df_array)
new_df.to_excel(writer,'sheet%s' % n)
writer.save()
# print(sheet)
在某些时候我没有收到错误,它正在正确读取和复制内容,但它会重写 master.xlsx 并覆盖旧的东西,而不是连接它。
编辑
合并正在运行。我现在的困难是我需要从一个单元格中获取数据,删除前 7 行,然后创建一个新列并将该数据添加到该列中的所有行(对于文档的长度)。
我认为让这变得困难的一件事是我必须使用read_html(),因为read_excel() 不起作用。我收到以下错误:
Traceback (most recent call last):
File "script.py", line 83, in <module>
sheet = pd.read_excel(f)
File "C:\Users\Kenny\AppData\Local\Programs\Python\Python36-32\lib\site-packages\pandas\io\excel.py", line 200, in read_excel
io = ExcelFile(io, engine=engine)
File "C:\Users\Kenny\AppData\Local\Programs\Python\Python36-32\lib\site-packages\pandas\io\excel.py", line 257, in __init__
self.book = xlrd.open_workbook(io)
File "C:\Users\Kenny\AppData\Local\Programs\Python\Python36-32\lib\site-packages\xlrd\__init__.py", line 441, in open_workbook
ragged_rows=ragged_rows,
File "C:\Users\Kenny\AppData\Local\Programs\Python\Python36-32\lib\site-packages\xlrd\book.py", line 91, in open_workbook_xls
biff_version = bk.getbof(XL_WORKBOOK_GLOBALS)
File "C:\Users\Kenny\AppData\Local\Programs\Python\Python36-32\lib\site-packages\xlrd\book.py", line 1230, in getbof
bof_error('Expected BOF record; found %r' % self.mem[savpos:savpos+8])
File "C:\Users\Kenny\AppData\Local\Programs\Python\Python36-32\lib\site-packages\xlrd\book.py", line 1224, in bof_error
raise XLRDError('Unsupported format, or corrupt file: ' + msg)
xlrd.biffh.XLRDError: Unsupported format, or corrupt file: Expected BOF record; found b'\n<html>\n'
【问题讨论】:
-
您可能想要
new_df = pd.concat(df_array)iirc...您只是一遍又一遍地将new_df分配给df... -
同意 Corley 的观点,` pd.concat(df)` 根本没有合并任何东西,而是只给你你手头的框架。但是
pd.read_excel不也处理 xls 文件吗? -
谢谢你,这很有意义并且帮助很大!我认为我走在正确的轨道上。我现在可以在文件末尾添加新数据。现在我想我需要在添加到数组之前发现前 7 行的删除。将使用最新代码更新问题。
-
我对 pandas 不太熟悉,但这听起来像是直接使用底层库(xlrd 用于阅读,XlsxWriter 用于写作)的相对简单的任务。但是,该错误似乎表明您的输入文件不是真正的 .xls 文件,而是有意命名为 .xls 的 HTML 文件。因此,我不明白您为什么说可以成功合并。数据是否必须首先被 pandas(通过任何方式)成功读取?
-
我想通了,我会尽快发布答案。
标签: python excel python-3.x pandas