XLRDError: File size is 0 bytes
代码实例的目的是将一个文件夹内的具有相同数据结构的Excel表格的数据汇合到一另外一张新表。
import os
import xlrd
import pandas as pd
import re
path = r'E:\data\data03' # 目录(放Excel表格的目录)
file_list = os.listdir(path)
FilePath=[]
for file in file_list: # 循环遍历列出所有文件名称
file_name = os.path.join(path, file) # 路径+文件名
#print(file_name)
FilePath.append(file_name)
newdata=pd.DataFrame()
for excelname in FilePath:
#print(excelname)
ptten=r"data03\\(.*)\.xlsx" #正则表达式相应要更改,获取文件名
str1=re.findall(ptten,excelname)
str_1=''.join(str1)
#print(str_1)
workbook = xlrd.open_workbook(excelname) # 打开第一个文件
sheet_name = workbook.sheet_names()
#print(sheet_name)
for i in sheet_name:
print("正在读取:"+excelname+" "+i+":sheet")
data= pd.read_excel(excelname,i,skiprows=2)#忽略前2行读取
data['部门']=str_1
data=data.set_index('部门')
newdata=newdata.append(data)
newdata.to_excel('E:\\data\\data05\\汇总数据.xlsx')
运行时出现如下错误:
---------------------------------------------------------------------------
---------------------------------------------------------------------------
XLRDError Traceback (most recent call last)
<ipython-input-11-7fea451eb95c> in <module>
13 str_1=''.join(str1)
14 #print(str_1)
---> 15 workbook = xlrd.open_workbook(excelname) # 打开第一个文件
16 sheet_name = workbook.sheet_names()
17 #print(sheet_name)
通过分析发现:该文件夹存在一个word文件,而出错的语句是针对xlrd格式的文件,将word文件删除或移动到其他路径即可。或者通过正则表达式过滤。
workbook = xlrd.open_workbook(excelname)
正则表达式过滤:
path = r'E:\data\data05' # 修改点1 目录(放Excel表格的目录)
file_list = os.listdir(path)
FilePath=[]
for file in file_list: # 循环遍历列出所有表格文件名称
file_name = os.path.join(path, file) # 路径+文件名
#print(file_name)
ptten=r"data05\\(.*)\.xls" #修改点2 正则表达式截取文件名
str1=re.findall(ptten,file_name)
str_1=''.join(str1)
if len(str_1)>0: #str_1为空,长度则为0
FilePath.append(file_name)
else:
continue