【问题标题】:write in file is not complete without quitting the IDLE(Python GUI)如果不退出 IDLE(Python GUI),写入文件是不完整的
【发布时间】:2010-04-17 14:39:13
【问题描述】:

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

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

【问题讨论】:

  • fo.close 返回函数对象,如a = fo.close 赋值。如果你想真正调用它,你需要括号:fo.close(),或者,等效地,a()

标签: python file python-idle


【解决方案1】:

可能是笔误,但应该是:

fo.close()

那么它应该可以工作了。

您也可以使用with 语句语法(better example):

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

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

(不用'abc'+'\n',直接写'abc\n'

【讨论】:

    【解决方案2】:

    你可以试试

    fo.flush()
    

    也许

    os.fsync()
    

    写入文件对象后确保所有文件操作都刷新到磁盘。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-27
      • 2019-05-16
      • 2013-10-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多