Search code examples
pythoninvocationenv

Python encountering unexpected ')` in very short program


Python is seeing some problem with how I am opening a file with the code below

if __name__ == "__main__":
    fileName = sys.argv[1]
    with open(fileName, 'r') as f:
       for line in f:
           print line

It is producing the error

./search.py: line 3: syntax error near unexpected token `('
./search.py: line 3: `  with open(fileName, 'r') as f:'

Am I missing an import? What could be the cause of this?

EDIT: OS - CentOS, Python version 2.6.6

Not sure how I installed, I am running an image from a .edu openstack site. Not sure of the distribution, binaries, ...


Solution

  • You must add import sys in order to use sys.argv. Check this out.

    I have tried this:

    chmod u+x yourfile.py
    ./yourfile.py
    

    and it gives me:

    ./jd.py: line 4: syntax error near unexpected token `('
    ./jd.py: line 4: `    with open(fileName, 'r') as f:'
    

    If you are doing ./search.py file then add at the beginnig of your file #!/usr/bin/env python. Otherwise, use python file.py input