首页 > 解决方案 > 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))

标签: python-3.xindexingenumerate

解决方案


代码的第一部分:我得到 num1 的结果为 6。对于代码的第二部分,当我自己运行它时,我得到 24,但当我使用第 1 部分运行它时,我得到 18。

显然,第二部分继续读取第一部分停止的文件。最小的变化是把

num2 += num1

在第二个循环之后,或者只是将第三个循环更改为for i in range(num1, num1+num2):. and num2 > num1第二个循环中的条件将被删除。


推荐阅读