python-3.x - 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() 放在循环内的写入代码中,则读取代码会按预期打印出添加到文件中的新行。这是正确的行为吗?如果是这样,为什么?
解决方案
该文件正在缓冲模式下运行。它在循环内工作的原因是它们的文件被重复打开并且缓冲区可能被刷新。如果您需要对文件的写入在阅读器中快速可见,则可以在使用buffering=0
关键字参数打开文件时禁用缓冲。这应该使新行在阅读器中快速可见。您也可以显式调用编写器f.flush()
。有关更多详细信息,请参阅open() 上的文档。
推荐阅读
- dart - Flutter 每次都运行基本的演示应用程序
- c# - JsonIgnore 属性不适用于 ASP.NET MVC 实体的一个属性
- c++ - 标识符“__readgsqword”未定义 - Visual Studio 2017
- html - 在 RAILS_ENV=生产服务器上不正确显示 GUI
- javascript - 为什么将 React 组件存储为变量或状态是不好的设计实践
- python - 10.13 High Sierra OSX - Python mprotect 在授予 exec 权限时总是失败,使用 ENOMEM
- nginx - localhost 发送了无效响应。ERR_INVALID_HTTP_RESPONSE
- python - tesseract中的图像太大错误
- c# - Office 365 App Only Auth MVC c#
- node.js - 我们在 ubuntu 16.04 上安装了 Nodejs 8。结果 npm 也被安装了。稍后当我们输入 npm 时,我们收到错误 URIError: URI malformed