python - 在python中拖尾文件
问题描述
如何从 python 中“关注”类似于 tail 命令的文件?例如,我认为以下内容会起作用:
def tail(filepath):
source = open(filepath)
source.seek(0,2)
while True:
chunk = source.readline()
yield chunk
source.close()
但是,当这些行被添加并保存到相关文件中时,它似乎并没有出现在“新行”上。在python中尾随文件的正确方法是什么?
解决方案
你可以使用这样的东西:
import os
from time import sleep
filename = 'file.test' # filename to 'follow'
with open(filename) as file:
st_size = os.stat(filename)[6]
file.seek(st_size) # move to the eof
while True:
where = file.tell() # save eof position
line = file.readline()
if not line: # if there is no new line
sleep(1)
file.seek(where) # move back
else: # if there is a new line
print(line.replace('\n','')) # print new line
推荐阅读
- git - 将 Visual Studio Code 设置为 Docker 开发容器内的默认 git 编辑器
- swift - 从核心数据 Swift 中获取最新项目
- regex - 需要 Hive 等效于 oracle 的 regexp_extract 来提取模式之间的文本
- c# - Linq Count() 超时 - 执行超时已过期。操作完成前超时时间已过或服务器无响应
- r - 删除组中在 R 中第一次出现多个因子变量水平之后的所有行
- shell - Jenkins 文件中用于 SQL 查询的错误处理
- sql - 在 SQLite 中比较和获取记录时出错
- javascript - 如何从包含所有页面的 JS 代码的单个 JS 文件中使用特定于某些页面的 JS 代码?
- android - 如何将 multi_image_picker2 `Asset` 转换为 `File` 对象?
- python - Python MongoDB更新索引处的数组元素