以下代码作为线程的一部分运行。当文件打开并且我们继续追加文件时,文件大小会正确增加,但该行是空的。行和文件大小都打印在第 5 行。无法理解 io 模块中的问题是什么。
with io.open(file_path, 'r', encoding='utf-8') as file:
file.seek(0, 2) # Seek to the end of the file
while not self._stop_event.is_set():
line = file.readline()
print(f"LINE = {line} FILE SIZE = {os.path.getsize(file_path)}") #LINE 5
if not line:
time.sleep(1)
else:
print(f"LINE : {line.strip()}")
我尝试打开该文件并继续追加内容。当我们不断向文件中添加新行时,它会不断增加文件大小。无法知道具体问题出在哪里。
您的代码不显示您如何附加到文件。
请注意,打开文件进行写入(在文本模式下)将被缓冲。因此,在写入每一行之后,刷新缓冲区非常重要。如果写入的数据包含回车符或换行符,则要么以行缓冲模式打开。
这是对您似乎正在尝试执行的操作的模拟,效果符合预期:
from threading import Thread
from time import sleep
from sys import stdout
RUN = True
FILENAME = "foo.txt"
def tail():
with open(FILENAME) as fd:
fd.seek(0, 2)
while RUN:
if line := fd.readline():
# stdout is line-buffered
# therefore, as our data has a newline character at its end, there's no need to flush
stdout.write(line)
sleep(0.25)
if __name__ == "__main__":
(thread := Thread(target=tail)).start()
# By opening the file in line-buffered mode, there's no need to flush
# providing the output contains either a carriage return or newline.
# If the file is opened in text mode without buffering=1 then it will
# be necessary to flush after each write
with open(FILENAME, "a", 1) as fd:
for i in range(10):
fd.write(f"Line {i}\n")
sleep(1)
RUN = False
thread.join()
输出:
Line 0
Line 1
Line 2
Line 3
Line 4
Line 5
Line 6
Line 7
Line 8
Line 9
注:
每条输出线之间会有~1s的间隔