Printing/writing an integer to a file
Gabriel Genellina
gagsl-py at yahoo.com.ar
Thu Nov 16 21:21:57 EST 2006
At Thursday 16/11/2006 22:33, PS wrote:
>Friends,
>
>I am new to python and did search on the web on how to achieve this:
>( I am trying to append the line numbers to all the lines of a file for now)
But you forget to say what went wrong... Next time, post the error
message including the full traceback.
Using my crystal ball I can see a few problems here:
>import os, sys
>
>fileName = os.path.join("C:", "temp", "x1.txt")
>fileobject = open(fileName, 'r')
>outputDir = "C://temp//"
>linenumber = 0
>fileName1 = outputDir + " x2.txt"
I see that you already know how to build properly a file name using
os.path.join - well, some lazyness is ok...
>fileobject1 = open(fileName1, 'w')
>while (1):
> L = fileobject.readline()
> if L=="":
> print "**Done"
> break
Usually that's written as:
for L in fileobject:
... do something ...
else:
print "** Done"
for is used to iterate over some sequence (or iterator), and a file
acts as its own iterator, yielding one line at a time.
The else clause -optional- is executed when nothing remains to iterate.
> linenumber += 1
> fileobject1.write (ln)
> fileobject1.write(":: "+ L)
I think here is your problem. You want the line number (printed as
text), followed by two :, a space, and the original line contents. I'd use:
fileobject1.write("%d:: %s" % (linenumber, L))
>
>fileobject1.close()
>=============================================================
Enough for a good start. Happy pythoning!
--
Gabriel Genellina
Softlab SRL
__________________________________________________
Correo Yahoo!
Espacio para todos tus mensajes, antivirus y antispam ¡gratis!
¡Abrí tu cuenta ya! - http://correo.yahoo.com.ar
More information about the Python-list
mailing list