1

I'm trying to printout a few cell contents using the XLRD package in Python 2.7 using the Spyder IDE to create a script. I'm seeing a syntax error while using the command print sheet.cell_value() on the IDE while it seems to return correct values when used from the windows command prompt. The error message I see is below:

print sheet.cell_value(0, col)
          ^
SyntaxError: invalid syntax

My code:

from __future__ import print_function
import xlrd

file_name="C:/Users/Documents/Python Learn/1.xlsx" 
workbook=xlrd.open_workbook(file_name)
sheet=workbook.sheet_by_index(0) 
NumberOfRows=sheet.nrows
NumberOfColumns=sheet.ncols
for col in range(sheet.ncols):
    print sheet.cell_value(0, col)
Tony Babarino
  • 3,355
  • 4
  • 32
  • 44

1 Answers1

2

You said from __future__ import print_function. That means that print is no longer a statement, and print ... with no parentheses is invalid syntax. Just add the parentheses:

for col in range(sheet.ncols):
    print(sheet.cell_value(0, col))
zondo
  • 19,901
  • 8
  • 44
  • 83
  • I'm not clear if importing a function transforms the 'print' from statement to something else, maybe a method. Could you please elaborate a bit more on this basic or point me to the resource that I can read. Thanks a lot, it does help to understand the discrepancy for a new learner like me. – pythonprogrammersud Apr 19 '16 at 09:40
  • @pythonprogrammersud: The `__future__` module is a special module that changes what valid syntax is. In this case, yes you could use `print_function`, but it also replaces the `print` statement with a function, so it can no longer be used as a statement, but must be used as a function: with parentheses. [Further reading](http://stackoverflow.com/a/7075121/5827958). – zondo Apr 19 '16 at 10:38