2

Been working at this for quite a while, and I haven't found any examples on this site or any others that seem relevant. I have a list, and what I'm trying to do is pretty simple I think. I just need to search that list to find the key word "Buffer Log". Once I find that keyword, I need to print every line from that line, until the end of the list. Any direction at all would be very much appreciated. It seems like I'm pretty close.

logfile = open('logs.txt', 'r')
readlog = logfile.readlines()
logfile.close()

lines = []
for line in readlog:
    lines.append(line)


for x in lines:
    if "Log Buffer" in x:
       z =lines.index(x)
       print(lines[z:]
1
  • What is the current output? Commented Mar 14, 2019 at 21:35

2 Answers 2

6

Firstly, the code:

lines = []
for line in readlog:
    lines.append(line)

Is unnecessary because readlog is already a list. You can try something along the lines of this:

found = False
for line in readlog: # because this is already a list
    if "Log Buffer" in line:
        found = True # set our logic to start printing
    if found:
        print(line)
Sign up to request clarification or add additional context in comments.

Comments

1

You don't need the for loop in which yoú're creating one more list called lines.

You can use enumerate() to keep track of which line number you are at, while searching for the line that contains 'Log Buffer'

When you find the line that contains 'Log Buffer', just remember that line number, exit the loop, and then print all lines from readlog starting from that line number.

logfile = open('logs.txt', 'r')
readlog = logfile.readlines()
logfile.close()

for i,x in enumerate(readlog):
    if 'Log Buffer' in x:
        z = i # Remember the value of i for which the line had 'Log Buffer'
        break # Exit the loop.

print (*readlog[z:])  # Move your print statement outside the loop.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.