写后从文件中读取,关闭前 [英] Read from file after write, before closing

查看:23
本文介绍了写后从文件中读取,关闭前的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在写入后,在关闭它之前从最初为空的文件中读取.这在 Python 中可行吗?

I'm trying to read from an originally empty file, after a write, before closing it. Is this possible in Python?

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

使用 f.flush() 刷新似乎不起作用,因为最终的 f.read() 仍然没有返回任何内容.

Flushing with f.flush() doesn't seem to work, as the final f.read() still returns nothing.

除了重新打开文件之外,还有什么方法可以读取文件中的foobar"?

Is there any way to read the "foobar" from the file besides re-opening it?

推荐答案

您需要使用 seek():

You need to reset the file object's index to the first position, using 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())

这将使文件可供读取.

这篇关于写后从文件中读取,关闭前的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆