Akhil S
Akhil S

Reputation: 29

Python read() returns empty results

Whenever I'm trying to run this python code, it returns a blank result / empty result. Can anyone help me with understanding why this happens?

#!/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()

Upvotes: 2

Views: 112

Answers (1)

larsks
larsks

Reputation: 311576

When you write to a file, the current file position is located at the end of the file. If you call read without explicitly setting the file position, you'll get back an empty result because you're already at the end of the file.

To read the data you've already written, you need to instruct Python to start reading from the beginning of the file using the seek method:

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

Alternately, you can close the file and then re-open it for reading.

Upvotes: 2

Related Questions