开发者

write in file is not complete without quitting the IDLE(Python GUI)

I want to write something in a file. for example,

fo=open('C:\\Python\\readline_test.txt','a')
for i in range(3):
 st='abc'+'\n'
 fo.write(st)
fo.close

then I open this python file in IDLE, and click "Run Module". There is no error message but I find the writing is not complete if I didn't quit IDLE. How can I complete t开发者_如何学编程he file writing without quitting the IDLE? Thanks.

(I use Python 2.6.2 on Windows XP.)


Maybe a typo, but it should be:

fo.close()

Then it should work.

Alternative you can use the with statement syntax (better example):

with open('C:\\Python\\readline_test.txt','a') as fo:
    for i in range(3):
        fo.write('abc'+'\n')

The file is automatically closed when leaving the with block.

(Instead of 'abc'+'\n', just write 'abc\n')


You can try using

fo.flush()

and mayby

os.fsync()

after writing to file object to ensure that all file operations are flushed to disk.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜