写入后,关闭前从文件读取


问题内容

我试图在写完之后从一个原来为空的文件中读取,然后关闭它。这在Python中可行吗?

with open("outfile1.txt", 'r+') as f:
    f.write("foobar")
    f.flush()
    print("File contents:", f.read())

冲洗f.flush()似乎不起作用,因为决赛f.read()仍未返回任何结果。

除了重新打开文件外,还有什么方法可以从文件中读取“ foobar”?


问题答案:

您需要使用以下命令将文件对象的索引重置为第一个位置seek()

with open("outfile1.txt", 'r+') as f:
    f.write("foobar")
    f.flush()

    # "reset" fd to the beginning of the file
    f.seek(0)
    print("File contents:", f.read())

这将使文件可供读取。