Search code examples
pythonmultithreadingfileio

File not overwritten though opened in 'w' mode in python?


As in everywhere this piece of code should overwrite content on the file with the value in the last_index variable because the file is opened in w mode.

from threading import *

def function():
    with open('important.cache', 'w') as f:
        while True:
            f.write(str(last_index))

mythread = Thread(target=function)
mythread.start()

but my important.cache file looks like this,

0000000000000000000000000000000000000011111111111111111111111111122222222222222222222222222222222222222333333333333333333333333333333333333333333333333333333333334444444444444444444444444444444555555555555555555

I want it to look like,

0

this should be overwritten in every cycle of the loop. So it can be

1

or

2

or

the value of the variable last_index at that time

Solution

  • You should maybe switch the order of your loops. It is true as you say that 'w' mode erases the content of the file, but it does it when you call the open function instead of when you call write.

    from threading import *
    
    def function():
        while True:
            with open('important.cache', 'w') as f:
                f.write(str(last_index))
    
    mythread = Thread(target=function)
    mythread.start()
    

    You'll see that sometimes the important.cache file will be empty. This is because the while loop is very very fast and it is erasing and writing the file very fast. For solving that, you should maybe call a small sleep after the write statement (time.sleep(0.01)) would probably work.