sidnical sidnical - 1 year ago 58
Python Question

Slice variable from specified letter to specified letter in line that varies in length

New to the site so I apologize if I format this incorrectly.

So I'm searching a file for lines containing

Server[x] ip.ip.ip.ip response=235ms accepted....

where x can be any number greater than or equal to 0, then storing that information in a variable named

I'm then printing this content to a
GUI and its way too much information for the window.

To resolve this I thought I would slice the information down with a
return line[15:30]
in the function but the info that I want off these lines does not always fall between 15 and 30.

To resolve this I tried to make a loop with

return line[cnt1:cnt2]

in a loop until
meets "S" and
meets "a" from accepted.

The problem is that I'm new to Python and I cant get the loop to work.

def serverlist(count):
with open("file.txt", "r") as f:
searchlines = f.readlines()
if 'f' in locals():
for i, line in enumerate(reversed(searchlines)):
cnt = 90
if "Server["+str(count)+"]" in line:
if line[cnt] == "t":
cnt += 1
return line[29:cnt]
except WindowsError as fileerror:

I did a
on the line reading because the lines I am looking for repeats over and over every couple of minutes in the text file.

Originally I wanted to scan from the bottom and stop when it got to
but this loop wasn't working for me either.

I gave up and started just running
and specifying the server number I was looking for instead of just running

Hopefully when I understand the problem with my original loop I can fix this.

End goal here:

file.txt has multiple lines with

<timestamp/date> Server[x] ip.ip.ip.ip response=<time> accepted <unneeded garbage>

I want to cut just the
and the response time out of that line and show it somewhere else using a variable.

The line can range from
and the same response times are checked every few minutes so I need to avoid duplicates and only get the latest entries at the bottom of the log.

Im sorry this is lengthy and confusing.

Answer Source

Here is my first approach:

def serverlist(count):
    with open("file.txt", "r") as f:
        for line in f.readlines():
            if "Server[" + str(count) + "]" in line:
                return line.split()[1] # split on spaces
    return False

print serverlist(30)
# ip.ip.ip.ip

print serverlist(";-)")
# False

You can change the index in line.split()[1] to get the specific space separated string of the line.

Edit: Sure, just remove the if condition to get all ip's:

def serverlist():
    ips = []
    with open("file.txt", "r") as f:
        for line in f.readlines():
            ips.append(line.split()[1]) # split on spaces
    return ips
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download