A limit to writing to a file from a loop?

Peter Otten __peter__ at web.de
Wed Feb 13 03:10:09 EST 2019


Steve wrote:

> My program reads from a text file (A), modifies the data, and writes to
> another file (B). This works until I reach about 300 writes and no more
> lines are written to file (B).
> 
> I had to create a Counter and increment it to 250 when it gets reset.
> 
> Upon reset, I close the file (B) being written and reopen it for append.
> 
> Then it accepts the entire list of lines of data.
> 
>  
> 
> Bizarre?

Maybe a misdiagnosis. If you are reading the file contents while it is still 
open some output may reside in a buffer that is invisible to the reading 
file object.

>             CycleCounter += 1
> 
>             if CycleCounter > 250:
> 
>               CycleCounter = 1

Try replacing the following two lines
 
>               DateReadings.close()
>               DateReadings=open("Date-ReadingsAndDoses.txt", "a")

with

                DateReadings.flush()

If that has the same effect as the close()/open() dance remove the flush(), 
too,  and ensure that the file is closed before you check its contents. The 
with statement is the established way to achieve that. Instead of

file = open(...)
do_stuff_with(file)
file.close()  # not called if there is an exception

write

with open(...) as file:
    do_stuff_with(file)
# at this point the file is guaranteed to be closed.

> 
>               DateReadings.write("{0:15} {1:>8} {2:>8} {3:>8} {4:<2}
>               {5:>8} {6:>8} {7:>10}".format
> 
>                               (ThisTimeDate, ThisReading, ThisDose1,
>                               ThisSensor, ThisTrend,
> 
>                                ThisTS, ThisPercent, SensorNumberDay2) +
>                                "\n")




More information about the Python-list mailing list