-1

I am trying to run a basic random sentence generator to test my web server for python... all it does is open 3 files and randomly pick a line from each.

It does run fine on my laptop but on the web server it fails and generates a syntax error for one part of the code (a part I got from another stack overflow question here - How to get line count cheaply in Python? ).

The error is:

  File "sentence.py", line 17
    with open(fname) as f:
SyntaxError: invalid syntax

And the part with the error is:

def file_len(fname):
    with open(fname) as f:
        for i, l in enumerate(f):
            pass
    return i + 1

The server is using Python 2.4.3

Does anyone see an immediate problem here?

Community
  • 1
  • 1
joep1
  • 325
  • 4
  • 18
  • 2
    The `with` statement wasn't introduced until Python 2.5 – Sean Vieira Sep 30 '14 at 14:04
  • Running such an old Python on a web server is probably not a good idea. Python 2.4.3 was released in 2006. The last bugfix for 2.4 was released 2008. I encourage you to update your Python to a more recent version. You will not only gain access to more features, but also get less bugs and more security fixes. – Steven Rumbalski Sep 30 '14 at 15:25

1 Answers1

3

The with statement is only available in Python 2.5 and newer:

New in version 2.5.

Use a try..finally construct instead:

def file_len(fname):
    f = open(fname)
    try:
        for i, l in enumerate(f):
            pass
    finally:
        f.close()
    return i + 1
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • Thanks - this worked great! Can't upgrade server yet as they won't let me... but they are going to sort it soon. For now this is a useful workaround. Sorry for the duplicate question... I'll be more careful in future. – joep1 Oct 01 '14 at 22:30