writing on file not until the end

Dave Angel davea at ieee.org
Sun May 24 19:46:28 EDT 2009


Alexzive wrote:
> Hello,
> I am a newby with python. I wrote the following code to extract a text
> from a file and write it to another file:
>
> linestring = open(path, 'r').read() #read all the inp file in
> linestring
>
> i=linestring.index("*NODE")
> i=linestring.index("E",i)
> e=linestring.index("*",i+10)
> textN = linestring[i+2:e-1] # crop the ELement+nodes list
> Nfile = open("N.txt", "w")
> Nfile.write(textN)
>
> unfortunately when I check N.txt some lines are missing (it only crop
> until "57, 0.231749688431, 0.0405121944142" but I espect the final
> line to be "242, 0.2979675, 0.224605896461". I check textN and it has
> all the lines until "242..")
>
> when I try Nfile.write(textN) again it writes some more lines but
> still not all!
> what is wrong whit this?
>
> Many thanks for your help!
> Alex
>
> the original file to crop (in path) looks like this:
>
> <snip>
>
>
>   
Is there a reason you used e-1 instead of e in the slice?  That's going 
to chop off the last newline.  And in some (broken) text viewers, you 
might not see the partial line.  Also, it'll behave a bit different in 
Windows than in one of the Unix variants, due to newline being 
represented by two characters instead of one.

e=linestring.index("*",i+10)
textN = linestring[i+2:e-1] # crop the ELement+nodes list





More information about the Python-list mailing list