Syntax error on another machine

Asked

Viewed 58 times

4

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

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

In which I seek the string "]L" in the output file1.txt and print the corresponding line.

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

Could you tell me if this is because of a version or a compiler or something? Or if there is another way to make the same resource?

Error:

$ python teste.py

 File "teste.py", line 1
    with open('saida1.txt') as saida:
            ^
SyntaxError: invalid syntax

2 answers

4


The problem is in context manager (with ...) which does not exist before python 2.5, try 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()
  • Thanks for the feedback, my first attempt was this, but it does not read the file in the same way.

  • @Mauríciosalin , I will put the way to read line by line

  • Thank you so much @Miguel

  • Nothing @Mauríciosalin, I’m glad you decided... However if this is code to run with different versions of python it is better to always leave it like this, or to do a check at the beginning of the code to see which version will be interpreted

  • Done, I already suspected it was the version, however I had not found yet other ways to do the same thing.

2

Good morning, I’m not from are python, but I googled it and I 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

The open was only introduced in version 2.5+ Try using the code above, and a searched on the 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

  • Thanks for the feedback Bruno, really the problem is in the version, I will try this other way and read the topics sent, thanks!

  • I’m glad you helped, I’m not from the area as I said, but trying to help only costs time anyway. Success for you and your application.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.