Reputation: 101
I have a program that polls a servers current Wi-Fi status every minute, and saves that info to a .txt file. The output is:
*****CURRENT WIFI SIGNAL STRENGTH*****: Link Quality=57/70 Signal level=-53 dBm
The text file contains many of these lines. What I'm trying to accomplish is: -Find the signal dBm values in all the lines, and append them to an array so I can then I can do other functions such as sort and average. I can't seem to get it working quite right.
Does anyone know how to do this?
Thank you!
Upvotes: 2
Views: 1515
Reputation: 799
signal_levels = []
try:
with open("file.txt") as fh:
lines = fh.readlines()
except IOError as err:
# error handling
Then you can either make use of the re
module:
for line in lines:
matches = re.search(r'Signal level=(-?[0-9]+) dBm$', line)
if matches is None:
# possible error handling
signal_levels.append(int(matches.group(1)))
Or without it (inspired by heinst's answer):
for line in lines:
try:
value = int(line.split('=')[-1].split()[0])
signal_levels.append(value)
except ValueError as err:
# possible error handling
Upvotes: 2
Reputation: 15
Assuming that the signal level is the only negative number on any line you could use a regular expression with the findall function to search for all negative numbers in the file and return them as a list of strings (based on MC93's answer).
import re
f_in = open("input.txt", "r")
signal_levels = re.findall("-\d+", f_in.read())
Alternatively, you could get a list of ints with a list comprehension.
signal_levels = [int(n) for n in re.findall("-\d+", f_in.read())]
Upvotes: 1
Reputation: 8786
I would go through each line in the file and split the line at =
, then get the last value, split it at the space, and then get the first value which would yield -53
.
strengthValues = []
f = open("input.txt", "r")
fileLines = f.readlines()
for line in fileLines:
lineSplit = line.split('=')
strengthValues.append(lineSplit[-1].split()[0])
print strengthValues
Or list comprehension:
f = open("test.txt", "r")
fileLines = f.readlines()
strengthValues = [line.split('=')[-1].split()[0] for line in fileLines]
print strengthValues
Upvotes: 2