Python错误排除

使用pandas的read_excel函数读取.xls格式的Excel文件,部分文件提示错误

'utf-16-le' codec can't decode bytes

处理方法主要如下:

  1. 把xls另存为xlsx就可以正常读取。测试可行,但文件太多,也不知道哪个会出现错误,批量不可信。
  2. 使用xlwings,批量可行
import pandas as pd
import xlwings as xw
import re
import os

path = r'目录'
files = [path + '\\' + i for i in os.listdir(path)]

app = xw.App(visible=False, add_book=False)  # 界面设置
app.display_alerts = False  # 关闭提示信息
app.screen_updating = False  # 关闭显示更新

title = []
for file in files:
    num_file = file.split('\\')[6].split('.')[0] # 文件名前的数字
    
    wb = app.books.open(file)  # 使用xlwings库
    cell = wb.sheets('sheet1').range('A1').value # (1,1)单元格
    cell = re.sub(r'\n|/',r'',cell) # 换行、斜杠 替换
    wb.close()
    title.append(cell)  # 保存表格的全名
    name_nospace = re.sub(r'\d.*\d\s+|\s',r'',cell) # 删除数字、空格
    newname = path + '\\' + num_file + ' ' + name_nospace + '.xls'
    os.rename(file, newname)

app.quit()

allxlsname = path + '\\' + '0表格名汇总.txt'
f = open(allxlsname, 'w', encoding='utf-8')
f.write('\n'.join(title))
f.close()    

xlwings使用的错误

有时候会出现错误:

expected string or bytes-like object

这是re提示的错误!
打开xls文件没任何问题,可是就是读不出单元格的内容,无值。在re.sub的时候出错。

用pd.read_excel读取相同的xls文件,提示错误

index 0 is out of bounds for axis 0 with size 0

该单元格读不出来,但是打开能看到一切正常,奇诡

posted @ 2022-12-08 15:49  hzworld  阅读(156)  评论(0编辑  收藏  举报