【问题标题】:Unable to write data into a file using python无法使用python将数据写入文件
【发布时间】:2014-03-13 20:35:13
【问题描述】:
outfile = open(inputfile, 'w')
outfile.write(argument)
outfile.flush()
os.fsync(outfile)
outfile.close

这是代码 sn-p。我正在尝试将某些内容写入 python 中的文件。但是当我们打开文件时,没有写入任何内容。我做错什么了吗?

【问题讨论】:

  • 你为什么要刷新stdout,而不是关闭文件对象?
  • 对不起。这是一个错误
  • 你为什么将输出文件命名为输入文件?
  • 它是一个脚本,还是你在 python shell 中尝试?如果它是一个脚本,文件应该在退出时自动关闭,所以这不应该是问题

标签: python linux file


【解决方案1】:

您没有调用outfile.close 方法。

这里不用flush,正确调用close即可:

outfile = open(inputfile, 'w')
outfile.write(argument)
outfile.close()

或者更好的是,使用文件对象作为上下文管理器:

with open(inputfile, 'w') as outfile:
    outfile.write(argument)

这都是假设argument 不是空字符串,并且您正在查看正确的文件。如果您在 inputfile 中使用相对路径,则使用什么绝对路径取决于您当前的工作目录,您可能正在查看错误的文件以查看是否已写入内容。

【讨论】:

  • 不应该在脚本退出时自动关闭(并刷新)文件吗?
  • @SunnyNanda:是的,当 Python 退出时文件也会被关闭。不过,问题中没有提到这一点。我还提到,假设argument 不是空字符串。
  • @SunnyNanda:添加了另一个假设; OP 正在查看正确的文件。
  • 谢谢马丁·彼得斯。您的第二个选项有效!
  • @user2599593:那么第一个也可以;所有file.__exit__() 所做的就是调用self.close()file.__exit__()with 块结束时被调用。
【解决方案2】:

试试

outfile.close()

注意括号。

outfile.close

只会返回函数对象而不做任何事情。

【讨论】:

    【解决方案3】:

    在刷新或关闭文件之前,您不会看到写入其中的数据。在您的情况下,您没有正确刷新/关闭文件。

    * flush the file and not stdout - So you should invoke it as outfile.flush()
    * close is a function. So you should invoke it as outfile.close()
    

    所以正确的 sn-p 应该是

      outfile = open(inputfile, 'w')
      outfile.write(argument)
      outfile.flush()
      outfile.close()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多