[Tutor] Question

ALAN GAULD alan.gauld at btinternet.com
Fri Jul 13 08:27:32 CEST 2007


Including the list...

----- Original Message ----
From: Que Prime <queprime at gmail.com>
To: Alan Gauld <alan.gauld at btinternet.com>

> Thank you Alan, but I'm still having difficulty.  


> I think you mean this but there must be something that I'm misunderstanding.

>  


> print "Creating txt file"
> tfile = open("25.txt", "w")

> for i in range(25):
>    tfile.write i:
>        str (i)(\n)

> tfile.close()    



Close, but you are still making it too difficult :-)

Try

tfile.write(str(i)+'\n')

OR

tfile.write( "d\n" % i)

HTH,

Alan G.
 

On 7/12/07, Alan Gauld <alan.gauld at btinternet.com> wrote:
"Que Prime" <queprime at gmail.com> wrote

>   Here is what I have so far but can't seem to get the loop and

> write correct.

I suspect you have used another language before and
Python's for loop is foxing you.

> print "Creating txt file"
> tfile = open("25.txt", "w")

>
> for i in range(25):
>    x = int(1)

You don;t need to convert to an int, i is already an int.
But worse, you are here converting the number 1 to
an int every time through the loop. I don't think thats

what you want! range(25) will produce a list of numbers
from 0 to 24. The for loop will set i to each number in
turn.

>    tfile.writelines("x\n")

And writelines expects a list of strings but you are

giving it one string. You only need write() here. And
of course you don't need x so you can just write
the string version of i: str(i) plus a new line (\n)

>    x += 1

And you don't need this at all because the loop

will automatically get the next number.

> tfile.close()

Try those changes, it should simplify things significantly.

You might find a quick read through my loops and file
handling topics useful too.


--
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld

_______________________________________________

Tutor maillist  -  Tutor at python.org
http://mail.python.org/mailman/listinfo/tutor






-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070713/ca208b79/attachment-0001.htm 


More information about the Tutor mailing list