Windows 10上的Python 3.7.0与open()的异常行为

时间:2018-08-24 20:16:50

标签: python-3.x

我是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()放入循环内的写入代码中,则读取的代码会打印出来 新行按预期方式添加到文件中。这是正确的行为吗?如果是这样,为什么?

1 个答案:

答案 0 :(得分:1)

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