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

时间:2014-03-02 13:08:47

标签: python file

我正在尝试在写入之后从原始空文件中读取,然后关闭它。这在Python中是否可行?

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

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

除了重新打开文件之外,有没有办法从文件中读取“foobar”?

3 个答案:

答案 0 :(得分:8)

您需要使用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())

将使文件可以从中读取。

答案 1 :(得分:3)

文件对象跟踪文件中的当前位置。您可以使用f.tell()获取并使用f.seek(position)进行设置。

要再次从头开始阅读,您必须使用f.seek(0)将位置设置为开头。

http://docs.python.org/2/library/stdtypes.html#file.seek

答案 2 :(得分:2)

在阅读之前回到文件的开头:

f.seek(0)
print f.read()
相关问题