![](/img/trans.png)
[英]Reading excel file with pandas in python how to fix : FileNotFoundError(2, 'No such file or directory')
[英]How to fix an encoding error reading an Excel file
我正在嘗試為自己制作一個腳本,將 excel 文件上傳到 postgre 數據庫。 源文件必須是 xlsx(不能是 csv)。 我的腳本可以處理大多數文件,但有一個......有一列文本(長句)。 特別是對於這個文件,我收到了這個錯誤:
26 """
27
---> 28 cursor.copy_expert(sql=sql_statement % tbl_name, file=my_file)
29 print('file copied to db')
30
QueryCanceled: COPY from stdin failed: error in .read() call: UnicodeDecodeError 'charmap' codec can't decode byte 0x81 in position 6918: character maps to <undefined>
CONTEXT: COPY clean_file, line 1
根據我的搜索,這個錯誤通常是由於編碼引起的,因此我確實嘗試了一堆編碼類型,如 utf-8、latin1、cp850、cp1252.. 但都沒有用。 而不是我一直試圖找到正確的編碼,我認為實際識別“麻煩”字符並在 excel 文件中替換它(替換)會更容易......我如何找到這個字符? “......在 position 6918......”是模糊的。 我有辦法找到它嗎? 我選擇的上傳庫是 psycopg2(我必須 ul 到 postgre 數據庫)。 該腳本在沒有相關列的情況下工作正常......所以很明顯其中一個單元格內的某些東西導致了這個問題
通過在 open 語句中添加 encoding='utf8' 以及 pd.read_excel 語句修復了錯誤 df[file] = pd.read_excel(data_path + file, encoding="ISO-8859-1") my_file = open(file,編碼='utf8')
我最近在嘗試讀取.xlsx
文件時遇到了這個問題
我的解決方案:
pip install openpyxl
然后讀取文件如下:
df = pd.read_excel(file_path, index_col=None, engine='openpyxl')
我很樂意提供幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.