【问题标题】:Python read() returns empty resultsPython read() 返回空结果
【发布时间】:2021-03-06 05:38:48
【问题描述】:

每当我试图运行这个python 代码时,它都会返回一个空白结果/空结果。谁能帮我理解为什么会发生这种情况?

#!/bin/python

import re
import time
import io

timecheck = open("/tmp/some.log", "r")
storeout = open("/tmp/storeout.txt", "w+")

for line in timecheck:
    if re.match("(.*)(Alarm obtained - type: KPI_CALCULATION)(.*)", line):
        out1 = line
        print >> storeout, line,

time1 = out1[11:19]
time2 = out1[164:172]
content = storeout.read()
print(content)
storeout.close()

【问题讨论】:

  • 请给我们一个日志部分
  • 日志文件包含以下条目:2020-11-23 13:10:57.596 petrosocial-esp-shutdown-handler DEBUG cpessShutdownAlarmConsumerService:54 - 获得警报 - 类型:KPI_CALCULATION,时间:2020-11 -23T12:51:00.000Z,KPI 警报类型:KPI_CALCULATION 2020-11-23 13:12:31.245 petrosocial-esp-shutdown-handler DEBUG cpessShutdownAlarmConsumerService:54 - 获得警报 - 类型:KPI_CALCULATION,时间:2020-11-23T13 :12:25.000Z,KPI告警类型:KPI_CALCULATION

标签: python linux python-2.7


【解决方案1】:

当您写入文件时,当前文件位置位于文件末尾。如果你在没有明确设置文件位置的情况下调用read,你会得到一个空的结果,因为你已经在文件的末尾了。

要读取您已经写入的数据,您需要使用seek 方法指示 Python 从文件开头开始读取:

storeout.seek(0)
content = storeout.read()

或者,您可以close 文件,然后重新open 以供阅读。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-01-17
  • 2021-09-15
相关资源
最近更新 更多