Question

import xlrd
book = xlrd.open_workbook("univ_list.xls")

I'm new to python. I'm trying to read a MS excel file that is in the same directory as my python script. Running the above code gives me a no such file or directory error.

I'll provide more information if needed.

Edit: code with full path upon request

import xlrd
book = xlrd.open_workbook("D:\Python_Scripts\univ_list.xls")

with corresponding error message

enter image description here

Was it helpful?

Solution 5

import xlrd
book = xlrd.open_workbook("univ_list.xls")

works perfectly well except that I need to replace xls with xlsx.

OTHER TIPS

You're getting hurt by string escapes. \ is an escape character for Python strings, so Python is attempting to find the \P and \u escape codes (among other things), which aren't going to be what you want.

The fix is either to escape the \ by changing the path to "D:\Python_Scripts\univ_list.xls", or to switch the string to an r"" (i.e. r"D:\Python_Scripts\univ_list.xls") string, which doesn't honor backslashes.

If python says you can't find a file, there are a couple steps you should take. The first is to make sure that the file exists. The first step is to make sure it's spelled correctly. Then, as suggested by AdamKG, make sure python can see it:

import os.path 
assert os.path.isfile(path_to_file)

just for supplement

Replaceing \ to / or \\ will be fine:

import xlrd
book = xlrd.open_workbook("D:/Python_Scripts/univ_list.xls")
 # book = xlrd.open_workbook("D:\\Python_Scripts\\univ_list.xls")
  • Because in Python strings, the backslash "\" is a special character, also called the "escape" character. You can read more in the document.

  • if you need \, actually you need \\.

The issue is that PyScripter sets the current directory. This is not the directory that your excel or python files is in (It will be probably be either your home, c:\ or the directory Pyscriper is in ( use os.getcwd() to get what it is).

Thus the fix is to provide the full path - but as shown in the other answers and comments this needs to be the string in raw form as Windows uses \ which do not mix well with the programming use of \ as an escape character in strings.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top