writing on file not until the end

Dave Angel davea at ieee.org
Mon May 25 16:06:17 CEST 2009

Alessandro wrote:
> <snip>
> I closed and restarted the python console. Now this code (with added
> "Nfile.close()" at the end) seems to work properly:
> linestring = open(path, 'r').read()
> i=linestring.index("*NODE")
> i=linestring.index("E",i)
> e=linestring.index("*",i+10)
> textN = linestring[i+2:e-1]
> Nfile = open("N.txt", "w")
> Nfile.write(textN)
> Nfile.close()
> thanks, Alex
Others had already mentioned close(), but I didn't bother, since it 
would be automatically closed when you exited the function, or finished 
the script.  I never dreamed you were running all this from the 
interpreter.  If so, why didn't you copy the prompts?

The close is best done explicitly, but it is implicit when the Nfile 
goes out of scope, or gets reassigned (like the new open).

However, the bug I described is still there.  Study the following, and 
try it:

def test():
    buf = "abcdefghijklmnopqrstg000"
    i = buf.index("d")
    e = buf.index("g", i+10)
    buf2 = buf[i+2:e-1]
    print buf2

running it produces the string:


Notice the 't' is missing.  If you're deliberately doing that, fine.  
But I doubt it.

More information about the Python-list mailing list