Question

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, ...

Was it helpful?

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

OTHER TIPS

The problem is that you aren't running your program with Python at all! When you do ./script (assuming that script is a text script, and not a binary program), the system will look for a line at the top of the file beginning with the sequence #!. If it finds that line, the rest of the line will be used as the interpreter of that script: the program which runs the script. If it doesn't find that line, the system defaults to /bin/sh.

So, basically, by omitting the magic line #!/usr/bin/python at the top of your script, the system will run your Python script using sh, which will produce all sorts of incorrect results.

The solution, then, is to add the line #!/usr/bin/python (or an equivalent line, like #!/usr/bin/env python) to the top of your Python script so that your system will run it using Python. Alternately, you can also always run your program using python search.py, instead of using ./search.py.

(Note that, on Linux, filename extensions like .py mean almost nothing to the system. Thus, even though it ends with .py, Linux will just execute it as if you wrote /bin/sh search.py).

Either:

  1. the first line of search.py should be a #! comment specifying the path to locate the python executable, usually [#!/usr/bin/env python](Why do people write #!/usr/bin/env python on the first line of a Python script? on-the-first-line-of-a-python-script). Usually this is #!/usr/env/bin python . Don't use a hardpath e.g. #/opt/local/bin/python2.7

  2. or else you can invoke as python yourfile.py <yourargs> ...


PREVIOUS: If import sys fails, post more of your file please.

Maybe your install is messed up.

Can you import anything else successfully, e.g. import re?

What are your platform, OS and Python version? How did you install? source? binaries? distribution? which ones, from where?

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