Search code examples
python-3.xindexingenumerate

line.strip() cause and effects to my second statement


I have 3 parts in my code. My first part tells me what line number the condition is on for line1. My second part tells me what line number the condition is on for line2. The last part makes the numbers as a range and prints out the range.

The first part of the code: I get a result of 6 for num1.

For the second part of the code I get 24 when i run it by itself but a 18 when i run it with part 1.

Then at the 3rd part i index the file and i try to get the proper lines to print out, but they dont work because my first part of my code is changing numbers when i have both conditions running at the same time.

Is there a better way to run this code with either just indexing or just enumerating? I need to have user input and be able to print out a range of of the file based off the input.

        #Python3.7.x
#
#
import linecache
#report=input('Name of the file of Nmap Scan:\n')
#target_ip=input('Which target is the report needed on?:\n')

report = "ScanTest.txt"
target_ip = "10.10.100.2"
begins = "Nmap scan report for"
fhand = open(report,'r')
beginsend = "\n"


#first statement
for num1,line1 in enumerate(fhand, 1):
    line1 = line1.rstrip()
    if line1.startswith(begins) and line1.endswith(target_ip):
        print(num1)
        print(line1)
        break
#second statement
for num2,line2 in enumerate(fhand, 1):
    line2 = line2.rstrip()
    if line2.startswith(beginsend) and num2 > num1:
        print(num2)
        print(line2)
        break
with open('ScanTest.txt') as f:
    linecount = sum(1 for line in f)

for i in range(num1,num2):

    print(linecache.getline("ScanTest.txt", i))

Solution

  • The first part of the code: I get a result of 6 for num1. for the second part of the code I get 24 when i run it by itself but a 18 when i run it with part 1.

    Obviously the second part continues reading the file where the first part stopped. The minimal change is to put

    num2 += num1
    

    after the second loop, or just change the 3rd loop to for i in range(num1, num1+num2):. The condition and num2 > num1 within the second loop is to be removed.