无法使用python将数据写入文件

2024-09-27 07:33:33 发布

您现在位置:Python中文网/ 问答频道 /正文

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

这是代码片段。我正试图用python写一些东西到一个文件中。但是当我们打开文件时,什么也没有写进去。我做错什么了吗?在


Tags: 文件代码closeosopenargumentoutfilewrite
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()

所以正确的片段应该是

^{pr2}$

您没有调用outfile.close方法。在

这里不需要刷新,只需正确地调用close:

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

或者更好的方法是,将file对象用作上下文管理器:

^{pr2}$

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

试试看

outfile.close()

注意括号。在

^{pr2}$

只返回函数对象而不真正执行任何操作。在

相关问题 更多 >

    热门问题