Reputation: 157
I'm really struggling to read an excel file in Python which is something I need to be able to do for coursework that I have set and I have found a method of doing it using xlrd however, I cannot get it work. I used cmd to install xlrd (pip install xlrd) and it was successful however, I am still unable to read Excel sheets into Python and I am unsure as to why it is not working, below is my code:
import xlrd
file_location = "C:/Users/Sean/Desktop/DADSA 17-18 COURSEWORK A MALE PLAYERS.csv"
workbook = xlrd.open_workbook(file_location)
Now every tutorial that I have watched this method has worked however, when I try to do it I get an error:
"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'"
Any help on this would be greatly appreciated,
Cheers
Upvotes: 1
Views: 5735
Reputation: 1975
Just to add to my comment I thought I would show some basic code to use the csv module to iterate over rows, also, pythons csv module documentation can be found here: 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
Upvotes: 1