>> s=str(a) >>> f.write(s) and the key.txt file remains empt...">

Error writing data to file in python

 a='aa'
>>> f=open("key.txt","w")


>>> s=str(a)
>>> f.write(s)

      

and the key.txt file remains empty .. why?

+2


a source to share


2 answers


Use

f.flush()

      

to clear the write to disk. Or, if you ended up with with f

, you can use



f.close()

      

to clear and close the file.

+10


a source


This problem can be completely eliminated by using the with statement :

with open("key.txt","w") as f:
    s=str(a)
    f.write(s)

      



The file will be automatically closed when the block is finished. By using with instruction , you don't need to worry about this type of errors creeping into your code.

+2


a source







All Articles