如果不退出 IDLE(Python GUI),写入文件未完成

发布于 2024-08-29 09:50:28 字数 296 浏览 1 评论 0原文

我想在文件中写一些东西。 例如,

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

然后我在 IDLE 中打开这个 python 文件,然后单击“运行模块”。 没有错误信息,但是如果我不退出IDLE,我发现写入不完整。 如何在不退出IDLE的情况下完成文件写入? 谢谢。

(我在 Windows XP 上使用 Python 2.6.2。)

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 the file writing without quitting the IDLE?
Thanks.

(I use Python 2.6.2 on Windows XP.)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

我爱人 2024-09-05 09:50:28

也许是一个错字,但应该是:

fo.close()

那么它应该可以工作。

或者,您可以使用 with 语句语法( 更好的示例):

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

离开时文件会自动关闭>with 块。

(不用 'abc'+'\n',只需编写 'abc\n'

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')

鹿! 2024-09-05 09:50:28

尝试使用

fo.flush()

and mayby以确保所有文件操作都刷新到磁盘。

os.fsync()

您可以在写入文件对象后

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文