繁体   English   中英

在 Python 中写入文件时从文件中读取?

[英]Read from file while it is being written to in Python?

我遵循了此处提出的解决方案

为了测试它,我分别使用了两个程序, writer.pyreader.py

# writer.py
import time

with open('pipe.txt', 'w', encoding = 'utf-8') as f:
    i = 0
    while True:
        f.write('{}'.format(i))
        print('I wrote {}'.format(i))
        time.sleep(3)
        i += 1
# reader.py
import time, os

#Set the filename and open the file
filename = 'pipe.txt'
file = open(filename, 'r', encoding = 'utf-8')

#Find the size of the file and move to the end
st_results = os.stat(filename)
st_size = st_results[6]
file.seek(st_size)

while 1:
    where = file.tell()
    line = file.readline()
    if not line:
        time.sleep(1)
        file.seek(where)
    else:
        print(line)

但是当我运行时:

 > python writer.py
 > python reader.py

读者将在作者退出后打印行(当我终止进程时)

有没有其他方法可以在编写内容时阅读内容?

[编辑]
实际写入文件的程序是一个.exe应用程序,我无权访问源代码。

您需要将写入/打印flush到文件中,否则它们将默认为块缓冲(因此您必须在用户模式缓冲区实际发送到操作系统进行写入之前写入几千字节)。

最简单的解决方案是在write后调用.flush

    f.write('{}'.format(i))
    f.flush()

这里有两个不同的问题:

  1. 操作系统和文件系统必须允许对文件的并发访问。 如果您没有收到错误,就是这种情况,但在某些系统上可能是不允许的

  2. 写入器必须flush其输出以使其到达磁盘,以便读取器可以找到它。 如果不这样做,输出将保留在内存缓冲区中,直到这些缓冲区已满,这可能需要几个 KB

所以作家应该成为:

# writer.py
import time

with open('pipe.txt', 'w', encoding = 'utf-8') as f:
    i = 0
    while True:
        f.write('{}'.format(i))
        f.flush()
        print('I wrote {}'.format(i))
        time.sleep(3)
        i += 1

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM