python-3.x - 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))
解决方案
代码的第一部分:我得到 num1 的结果为 6。对于代码的第二部分,当我自己运行它时,我得到 24,但当我使用第 1 部分运行它时,我得到 18。
显然,第二部分继续读取第一部分停止的文件。最小的变化是把
num2 += num1
在第二个循环之后,或者只是将第三个循环更改为for i in range(num1, num1+num2):
. and num2 > num1
第二个循环中的条件将被删除。
推荐阅读
- matlab - 如何有效地做一个托普利茨矩阵matlab
- python - 从 Sklearn 管道中提取具有特征名称的特征重要性
- python - celery 任务因 dlib cnn 人脸检测而失败
- javascript - 在隐身模式下运行 Chrome 时,JavaScript 源映射是否会受到影响?
- python - Pandas read_csv 具有正确的标题,但列名是 None
- excel - 使用 vba 将我当前帐户的余额从网页复制到 Excel
- audit.net - Audit.Net 实体框架 - 独立关联 [表多对多]
- javascript - 以不同的方式声明相同的函数会改变 Javascript 中的编译代码
- sql - 如何从另一个表插入一个表并使用函数
- r - DataTable 上的列未对齐;R 包装:DT