Search code examples
pythonxlsxlrd

python xlrd read xls file, what is the r in front of the path do?


I am using xlrd to read xls file in python. The code below doesn't work:

import xlrd
datapath = 'C:\Users\Box Sync\pyCodes\Practice\2015_ERCOT_Hourly_Load_Data.xls'
workbook = xlrd.open_workbook(datapath)
print workbook

But after I added a r in front of the path, it worked.

import xlrd
datapath = r'C:\Users\Box Sync\pyCodes\Practice\2015_ERCOT_Hourly_Load_Data.xls'
workbook = xlrd.open_workbook(datapath)
print workbook

What does the 'r' do here? Thanks!


Solution

  • while passing the datapath to xlrd, you should use escape sequence for the space included in the folder name Box sync. Adding an r at the starting of a string makes it a raw string , where the space is interpreted as space itself and you dont need any escape sequence. You can read more about raw strings on python documentation page. https://docs.python.org/2/reference/lexical_analysis.html#literals