开发者

error in writing data into file in python

开发者 https://www.devze.com 2022-12-29 06:34 出处:网络
a=\'aa\' >>> f=open(\"key.txt\",\"w\") >>> s=str(a) >>> f.write(s) 开发者_运维问答
 a='aa'
>>> f=open("key.txt","w")


>>> s=str(a)
>>> f.write(s)
开发者_运维问答

and still the key.txt file remains blank .. why?


Use

f.flush()

to flush the write to disk. Or, if you are done using f, you could use

f.close()

to flush and close the file.


This issue can be avoided completely by making use of 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 completes. Using the with statement you need not worry about this sort of bug creeping into your code.

0

精彩评论

暂无评论...
验证码 换一张
取 消