最近工作中要用到pandas讀取excel表格數據,遇到各種問題,在此借這此發布機會,統一記錄一下,以供同學們避免不必要的坑,
首先還是要把標題內容給解決,看代碼之前,一定要看完下面的話。
1、我主要遇到的問題是,在pandas打開excel時,會報錯,具體如下:

大概就是說:不支持的格式,或損壞的文件
其實文件沒有損壞,也是可以打開的格式。在我手動打開的時候會有這種提示:

保存時會有這種提示:

然后另存為之后,再打開就沒有這種提示了(這種提示Office打開也是會有的),pandas也可以正常讀取了,
然而如果有100個這種文件呢,保存100次?
怎么可能,學編程不就是為了解決,無聊重復繁瑣的事情,我就想到了用代碼進行格式轉換。
開始做格式轉換的時候,發現在格式轉換時會打開文件,還是會有彈窗,導致運行異常,無法轉換。
想到解決辦法是,啟動兩個進程,一個用來打開文件轉換,一個用來點擊確定,取消彈框,問題就解決了。
1 import win32com.client as win32 2 import os 3 import sys 4 import time 5 import win32api 6 import threading 7 import pythoncom 8 9 # 獲取桌面路徑‘文檔格式轉換’文件夾中所有文件 10 desktop = os.path.join(os.path.expanduser("~"), 'Desktop') 11 file_url = desktop+'\\'+'文檔格式轉換' 12 if not os.path.exists(file_url): 13 os.mkdir(m2) 14 list_file = os.listdir(file_url) 15 16 # 根據文件多少進行循環按鍵 Enter 17 def enter(): 18 for i in range(len(list_file)): 19 time.sleep(3) 20 win32api.keybd_event(13,0,0,0) 21 22 # excel 文件格式轉換,並另存為到‘待處理數據’文件夾中 23 def filegeshi(): 24 file_pending = desktop + '\\待處理數據' 25 if not os.path.exists(file_pending): 26 os.mkdir(file_pending) 27 # 循環文件列表,並循環轉換文件 28 29 for ex_name in list_file: 30 fname = file_url + "\\" + ex_name # 源文件路徑 31 save_as_file = file_pending + "\\" + ex_name # 保存文件路徑 32 pythoncom.CoInitialize() # 不加這句話會報錯,不知為什么 33 excel = win32.gencache.EnsureDispatch('Excel.Application') 34 wb = excel.Workbooks.Open(fname) # 打開要轉換的excel 35 wb.SaveAs(save_as_file, FileFormat = 56) # 文件格式 = 56 為 .xls 格式 36 #wb.SaveAs(save_as_file + 'x', FileFormat = 51) # 文件格式 = 51 為 .xlsx 格式 37 wb.Close() 38 excel.Application.Quit() 39 40 # 主程序 41 def file_conversion(): 42 # 如果‘文檔格式轉換‘文件夾中為空,則不處理,退出程序 43 if len(list_file) > 0: 44 # 開啟兩個線程,一個用來打開文件,一個用來按鍵 Enter 45 # 關鍵點 .join(),設置讓主線程等待所有的子線程都執行完畢,再執行 46 thread_1 = threading.Thread(target=filegeshi) 47 thread_2 = threading.Thread(target=enter) 48 thread_1.start() 49 thread_2.start() 50 thread_1.join() 51 thread_2.join() 52 else: 53 sys.exit() 54 file_conversion()
2、pandas 讀取文件時,其他天坑
最新pandas在讀取“.xlsx”時,會報錯:xlrd.biffh.XLRDError: Excel xlsx file; not supported
原因為,xlrd更新到了2.0.1版本,只支持.xls文件格式,
解決辦法,可以先卸載當前版本xlrd,安裝舊版本的 xlrd,
pip uninstall xlrd
pip install xlrd==1.2.0
好了,就這些吧,如有新的問題,再來記錄填坑
