[Tutor] Writing over a line in a text file

Kent Johnson kent37 at tds.net
Wed Jun 21 14:15:29 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.
> 
> Any ideas would be welcome.

Printing to a file will normally append to the file. To overwrite 
something in a file you have to seek to the location where you want to 
write and write the new information there. Here is a sketch which is 
probably wrong (!) because I don't ever have to do this...

f = open('log.txt', 'w')
print >>f, 'This line doesn\'t change'

where = f.tell() # remember the current location in f
for i in range(10):
   f.seek(where)
   print >>f, 'Counting...', i

This will break if the rewrite is not at the end of the file (overwrites 
in the middle of a file can't change the length of the file) or if 
another thread is also writing the file.

I wonder if a log file is the right mechanism for what you are trying to 
do? From your previous messages I guess you are doing a remote log. 
Maybe you should be monitoring log messages some other way? Or use tail 
to view the remote file so you just see the last line of the file?

Kent



More information about the Tutor mailing list