Question

So I have program that writes a lot to a text file:

line 395: f = open(filename, "a")
line 396: f.write("stuff")
line 397: f.write("more stuff")

It goes on writing stuff for about 800+ lines of f.write() being called over and over again

Ive been running the scrip periodically to check the results and it had been writing just fine to the text file. However, not adding any new code, just more f.writes all of the sudden my mac terminal has been throwing syntax errors that aren't really syntax errors:

line 1122 f.write("more stuff")
          ^ SyntaxError: invalid syntax

Its the EXACT same syntax the document uses for 500+ lines before that line. When I comment that line, the console will just throw up syntax error on the next line. Is it possible that the f before f.write is only good for xyz number of lines? I tried throwing the f declaration again (ie having it twice in the code), just before the throw up:

line 395: f = open(filename, "a")
line 396: f.write("stuff")
line 397: f.write("more stuff")
... ... ...
line 1110: f = open(filename, "a")
...
line 1122: f.write("more stuff")

Still throwing a random error that shouldn't be an error? Is it a memory issue?

Was it helpful?

Solution

You almost certainly ended line 1121 incorrectly somehow, and the Python interpreter expected the incomplete expression to be continued onto line 1122. When it could not parse 1122 as a continuation of 1121, that is what caused the syntax error, rather than anything particularly wrong with line 1122 itself.

Also, it is not true that "f.write is only good for xyz number of lines"; to demonstrate I wrote the following test-program generator:

import random
import string

GENFILE = "testwrite.py"
HEADER  = "with open('testout.txt', 'a') as f:\n"
BODY    = "    f.write(\"{}\")\n"
BODY_N  = 100000

def randstr(n = 1, ch=string.lowercase):
    return ''.join(random.choice(ch) for i in xrange(n))

def main():
    with open(GENFILE, 'w') as outf:
        outf.write(HEADER)
        for i in xrange(BODY_N):
            outf.write(BODY.format(randstr(10)))

if __name__=="__main__":
    main()

which created a program that looks like

with open('testout.txt', 'a') as f:
    f.write("ugakajlxkv")
    f.write("tskhodwgwr")
    f.write("vrqcrnxhcz")
    f.write("yijyqfyjug")
    f.write("gbsthkkkdc")
    f.write("vmupgtotoe")
    # ... 99,994 more lines

which runs quite happily.

OTHER TIPS

No it can't be a memory error, you would get a Memory exception of some time. I would check that you don't have some strange whitespace character immediately proceeding the offending write. Have a look at the code using od to see what is on or just before that line.

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