每当我尝试运行此 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()
最佳答案
写入文件时,当前文件位置位于文件末尾。如果您在没有显式设置文件位置的情况下调用 read
,您将得到一个空结果,因为您已经位于文件末尾。
要读取已写入的数据,您需要指示 Python 使用 seek
方法从文件开头开始读取:
storeout.seek(0)
content = storeout.read()
或者,您可以关闭
该文件,然后重新打开
它进行读取。
关于Python read() 返回空结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64969553/