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

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

问题描述

我试图在写完之后从一个原来为空的文件中读取,然后关闭它.在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?

推荐答案

您需要使用

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天全站免登陆