[Tutor] Writing over a line in a text file

Luke Paireepinart rabidpoobear at gmail.com
Wed Jun 21 14:24:22 CEST 2006


kieran flanagan wrote:
> Hi
>
> I have a question regarding writing text to a file. I am directing 
> output to a logfile. During one of the loops, I have a command that 
> will issue a message on how long it is waiting for by doing something 
> like this
>
> while something:
>
>                 print "\rNow waiting %s seconds .. " % seconds,
>                 sys.stdout.flush()
>                 print "\r                   ",
>
> I am trying to change my scripts so all info can be accessed via 
> logfiles. Is there any way I can direct the output to a logfile, as 
> above, without creating a new line for each print statement. I have 
> tried changing the sys.stdout to the logfile in question but the print 
> commands just force a new line for each print statement.
I don't understand what the commas atthe end of your print commands are for.
Nor do I understand what you're trying to do.
Are you trying to redirect stdout to a file?
why bother doing this?
why not just do

from time import sleep
from random import randint
f = file("log.txt","a")
while x < y:
    f.write("\nNow waiting %s seconds\n" % randint(0,4))
f.close()

Or do I misunderstand what your objective is?
Also, I believe \r is windows-only, and you should use \n all the time, 
or \r\n.


More information about the Tutor mailing list