Syntax error on another machine

4

I have a machine in which Python 2.6.6 is installed, in a certain part of a script I make the following command:

with open('saida1.txt') as saida:
    for line in saida:
        if "]L" in saida:
            print line

In which I search the string "L" in the file output1.txt and print the corresponding line.

Running the same script with the same command on another machine with Python 2.4.3 shows syntax error in "open" command.

Could you tell me if this is a version, compiler, or something? Or is there another way to do the same?

Error:

$ python teste.py

 File "teste.py", line 1
    with open('saida1.txt') as saida:
            ^
SyntaxError: invalid syntax
    
asked by anonymous 16.12.2016 / 13:50

2 answers

4

The problem is in the context manager (with ...) which does not exist before python 2.5, tries the following:

saida = open('file.txt', 'r')
lines = saida.readlines()
for line in lines:
    if "]L" in saida:
        print line
saida.close()

Or in order to cover possible exceptions:

fout = None
try:
    fout = open("tests.txt", "r")
    lines = fout.readlines()
    # fazer o que petendes 
finally:
    if fout is not None:
        fout.close()
    
16.12.2016 / 13:55
2

Good morning, I'm not from are python, but I gave a google and found this:

open isn't missing in 2.4. What's missing is the with statement (added in Python 2.5 as PEP-0343)

To do the same code without with:

fout = open("text.new", "wt")
# code working with fout file fout.close() Note the fout.close() is implicit when using with, but you need to add it yourself without

Open was only introduced in version 2.5+ Try using the code above, and a searchable open 2.4;

SyntaxError: invalid syntax on "with open" on python-2.4.3

What is the alternative for open in python 2.4.3

    
16.12.2016 / 13:57