[英]Reading Excel File In Python xlrd
我真的很難在 Python 中讀取 excel 文件,這是我需要能夠為我設置的課程作業做的事情,並且我找到了一種使用 xlrd 執行它的方法,但是,我無法讓它工作。 我使用 cmd 安裝 xlrd(pip install xlrd)並且它成功了,但是我仍然無法將 Excel 工作表讀取到 Python 中,我不確定它為什么不起作用,下面是我的代碼:
import xlrd
file_location = "C:/Users/Sean/Desktop/DADSA 17-18 COURSEWORK A MALE PLAYERS.csv"
workbook = xlrd.open_workbook(file_location)
現在,我看過此方法的每個教程都有效,但是,當我嘗試執行此操作時出現錯誤:
"Traceback (most recent call last):
File "C:\Users\Sean\Desktop\Data Structures Assignment 1\Tennis.py", line 3, in <module>
workbook = xlrd.open_workbook(file_location)
File "C:\Users\Sean\lib\site-packages\xlrd\__init__.py", line 162, in open_workbook
ragged_rows=ragged_rows,
File "C:\Users\Sean\lib\site-packages\xlrd\book.py", line 91, in open_workbook_xls
biff_version = bk.getbof(XL_WORKBOOK_GLOBALS)
File "C:\Users\Sean\lib\site-packages\xlrd\book.py", line 1271, in getbof
bof_error('Expected BOF record; found %r' % self.mem[savpos:savpos+8])
File "C:\Users\Sean\lib\site-packages\xlrd\book.py", line 1265, in bof_error
raise XLRDError('Unsupported format, or corrupt file: ' + msg)
xlrd.biffh.XLRDError: Unsupported format, or corrupt file: Expected BOF record; found b'MP01\r\nMP'"
對此的任何幫助將不勝感激,
干杯
只是為了添加到我的評論中,我想我會展示一些使用 csv 模塊迭代行的基本代碼,此外,pythons csv 模塊文檔可以在這里找到: https : //docs.python.org/3/library/csv .html
import csv
import xlrd
file_location = "C:/Users/Sean/Desktop/DADSA 17-18 COURSEWORK A MALE PLAYERS.csv"
if file_location.endswith(".csv"):
with open(file_location) as fp:
for row in csv.reader(fp):
# do something with rows
elif file_location.endswith((".xls", ".xlsx")):
workbook = xlrd.open_workbook(file_location)
# do something with workbook
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.