sarkar.shukla
sarkar.shukla

Reputation: 77

Getting error while reading excel sheet using python

from xlrd import *

book = open_workbook("File_1.xls")

#sheet = book.sheets()[0]           
#book.sheets() returns a list of sheet objects...     alternatively...
#sheet = book.sheet_by_name("qqqq") #we can pull by name
 sheet = book.sheet_by_index(0)     #or by the index it has in excel's sheet collection

r = sheet.row(0)                    #returns all the CELLS of row 0,
c = sheet.col_values(0)             #returns all the VALUES of row 0,

for i in xrange(sheet.nrows):
print sheet.row_values(5) 

I am reading a file which is in my desktop , but when I am running the script written in python it's giving error

  Traceback (most recent call last):
  File "C:\Python26\ReadXLS.py", line 6, in <module>
  book = open_workbook("File_1.xls")
  File "C:\Python26\Lib\site-packages\xlrd\__init__.py", line 449, in open_workbook
  ragged_rows=ragged_rows,
 File "C:\Python26\Lib\site-packages\xlrd\__init__.py", line 941, in biff2_8_load
 f = open(filename, open_mode)
  IOError: [Errno 2] No such file or directory: 'File_1.xls'

Upvotes: 1

Views: 7004

Answers (3)

Samy Vilar
Samy Vilar

Reputation: 11130

Verify that the script and file are in the directory, or specify the absolute path to your excel file.

Also note that if you try to open a file relatively, it will be done so using the current working directory where the python interpreter was initialized from.

I also recommend openpyxl http://packages.python.org/openpyxl/ if you ever need to work with the newer xlsx formats.

Upvotes: 1

pyfunc
pyfunc

Reputation: 66739

If ever, you are facing issue with paths, try finding your current path in the program

>>> import os.path
>>> import os
>>> os.curdir
'.'
>>> os.path.abspath(os.curdir)
'/Users/xxxx/temp'
>>> 

This is how it shows on Unix. It will show differently on Windows.

This way you will know, if that is the place where your current file is placed.

Code:

from xlrd import *
import os.path
import os
print os.path.abspath(os.curdir)

book = open_workbook("File_1.xls")
#sheet = book.sheets()[0]           
#book.sheets() returns a list of sheet objects...     alternatively...
#sheet = book.sheet_by_name("qqqq") #we can pull by name
 sheet = book.sheet_by_index(0)     #or by the index it has in excel's sheet collection

r = sheet.row(0)                    #returns all the CELLS of row 0,
c = sheet.col_values(0)             #returns all the VALUES of row 0,

for i in xrange(sheet.nrows):
print sheet.row_values(5) 

Upvotes: 1

Blender
Blender

Reputation: 298522

You need to cd Desktop before your run Python, as your error message says the file doesn't exist:

No such file or directory: 'File_1.xls'

Another fix would be to move the Python file into the same folder as the Excel file.

Upvotes: 2

Related Questions