Py学习  »  Python

在python中枚举和打印行。

Matt • 6 年前 • 1575 次点击  

好的,我正在构建一个小程序,它将帮助区分NMAP结果:

#Python3.7.x
#
#
#
#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.1"
begins = "Nmap scan report for"
fhand = open(report,'r')
beginsend = "Network Distance:"

for num1,line in enumerate(fhand, 1):
    line = line.rstrip()
    if line.startswith(begins) and line.endswith(target_ip):
    print(num1)
for num2,line in enumerate(fhand, 1):
    line = line.rstrip()
    if line.startswith(beginsend):
        print(num2)

在我的工作中,我要做的是得到扫描结果的第一部分“目标IP”,我希望我可以从那里读取行,直到TXT行出现中断。 这个代码现在为我做的就是把我想开始的行号给我。 在代码的第二部分,我尝试获取我需要的最后一位文本的行数。但它不会印刷。我不确定我是走正确的路还是不够努力。 简而言之,找到我的行并打印,直到文本出现中断。

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/38311
 
1575 次点击  
文章 [ 1 ]  |  最新文章 6 年前
John Gordon
Reply   •   1 楼
John Gordon    6 年前

第一个循环将排出文件中的所有行。当第二个循环尝试运行时,没有更多的行可读取,循环立即退出。

如果希望第一个循环在找到匹配行时停止,并允许第二个循环读取其余行,则可以添加 break 声明 if .

start_pattern = 'hello there'
end_pattern = 'goodblye now'
print_flag = False

with open('somefile.txt') as file:
    for line in file:
        if start_pattern in line:
            print_flag = True

        if print_flag:
            print line

        if end_pattern in line:
            break