2024-09-27 07:33:33 发布
网友
outfile = open(inputfile, 'w') outfile.write(argument) outfile.flush() os.fsync(outfile) outfile.close
这是代码片段。我正试图用python写一些东西到一个文件中。但是当我们打开文件时,什么也没有写进去。我做错什么了吗?在
在刷新或关闭文件之前,您不会看到写入其中的数据。在您的情况下,您没有正确地刷新/关闭文件。在
* 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()
所以正确的片段应该是
您没有调用outfile.close方法。在
outfile.close
这里不需要刷新,只需正确地调用close:
outfile = open(inputfile, 'w') outfile.write(argument) outfile.close()
或者更好的方法是,将file对象用作上下文管理器:
所有这些都假定argument不是空字符串,并且您正在查看正确的文件。如果您在inputfile中使用相对路径,则使用的绝对路径取决于当前的工作目录,并且您可能会查看错误的文件以查看是否有内容写入其中。在
argument
inputfile
试试看
outfile.close()
注意括号。在
只返回函数对象而不真正执行任何操作。在
在刷新或关闭文件之前,您不会看到写入其中的数据。在您的情况下,您没有正确地刷新/关闭文件。在
所以正确的片段应该是
^{pr2}$您没有调用
outfile.close
方法。在这里不需要刷新,只需正确地调用close:
或者更好的方法是,将file对象用作上下文管理器:
^{pr2}$所有这些都假定
argument
不是空字符串,并且您正在查看正确的文件。如果您在inputfile
中使用相对路径,则使用的绝对路径取决于当前的工作目录,并且您可能会查看错误的文件以查看是否有内容写入其中。在试试看
注意括号。在
^{pr2}$只返回函数对象而不真正执行任何操作。在
相关问题 更多 >
编程相关推荐