首页 > 解决方案 > Windows 10 上的 Python 3.7.0 使用 open() 出现意外行为

问题描述

我是 Python 新手,我看到了一些基于我使用过的其他语言的意想不到的东西。

此代码写入日志文件。

import datetime
import time

date = datetime.datetime.today().strftime('%Y-%m-%d')
mtime = time.strftime("%H:%M:%S")
myfile = "log_file." + date + ".txt"

# fh = open(myfile, "a")   # Read program won't read new records if the open
                           # is done outside the loop                     
for x in range(100):
  fh = open(myfile, "a")   # Read program works as expected if this open 
  mtime = time.strftime("%H:%M:%S")  
  msg = str (mtime + " This is entry number " + str(x+1) + "\n")
  fh.write(msg)
  time.sleep( 2 )

fh.close

此代码打印出写入日志文件的新记录

import datetime
import time

date = datetime.datetime.today().strftime('%Y-%m-%d')
myfile = "log_file." + date + ".txt"

# This reads through all the records currently in the file.

lastLine = None
with open(myfile,'r') as f:
        while True:
            line = f.readline()
            if not line:
                break
            # print(line)        
            lastLine = line

# This prints out all of the new lines that are added to the file.

while True:
    with open(myfile,'r') as f:
        lines = f.readlines()
    if lines[-1] != lastLine:
        lastLine = lines[-1]
        print(lines[-1])        
    time.sleep(1)

如果我将 open() 放在 for 循环之前的写入代码中,则读取代码永远不会看到新记录。

如果我将 open() 放在循环内的写入代码中,则读取代码会按预期打印出添加到文件中的新行。这是正确的行为吗?如果是这样,为什么?

标签: python-3.x

解决方案


该文件正在缓冲模式下运行。它在循环内工作的原因是它们的文件被重复打开并且缓冲区可能被刷新。如果您需要对文件的写入在阅读器中快速可见,则可以在使用buffering=0关键字参数打开文件时禁用缓冲。这应该使新行在阅读器中快速可见。您也可以显式调用编写器f.flush()。有关更多详细信息,请参阅open() 上的文档。


推荐阅读