如果语句在使用 nmap 时不工作 Python

If Statement not working Python while using nmap

我在使 if 语句正常工作时遇到了一些问题。在iplist.txt的末尾有一个空行,我不想运行,但由于某种原因,它仍然是运行ning。我尝试删除文件的最后一行,但它只删除最后一个合法行而不是空白行,我什至尝试删除空格、空行和空行,但它仍然会 运行 一行。最奇怪的是 if 块和 else 块中的空白 运行s。

 with open ("iplist.txt", "r") as file:
     filecontents = file.read()
     for line in filecontents.split('\n'):
      filename = (line) + ".txt "
      command = "nmap -O -oG " + ".\ips\" + (filename) + (line)
      print(command)
      print(filename)
      strlen = int (len(filename))
      print(strlen)
      compareline = line[:4]
      print(compareline)
      if compareline == beginline: #beginline is declared as 10.9 earlier in the file
       print("Testing 1..2...")
       os.system(command)
       filenameforos = (line + ".txt")
       #detailedosdetection = open(filenameforos)
       #next(filecontents)
      else:
       print("Testing...")
       del line
       #next(StopIteration)

这里是iplist.txt

的内容
10.9.10.38
10.9.10.45
10.9.11.10
#extra line
编辑

我试过了,但它没有 运行 循环,我确定我做错了。

with open ("iplist.txt", "r") as file:
 filecontents = file.read()
 lines = file.readlines()
 lines = [x.strip() for x in lines]
 print("Creating list")
 for line in lines:
  filename = (line) + ".txt "
  command = "nmap -O -oG " + ".\ips\" + (filename) + (line)
  print(command)
  print(filename)
  strlen = int (len(filename))
  print(strlen)
  compareline = line[:4]
  print(compareline)
  if compareline == beginline: #beginline is declared as 10.9 earlier in the file
   print("Testing 1..2...")
   os.system(command)
   filenameforos = (line + ".txt")
   #detailedosdetection = open(filenameforos)
   #next(filecontents)
  else:
   print("Testing...")
   del line
   #next(StopIteration)

Python 有一种读取单独行的方法。尝试

lines = file.readlines()
lines = [x.strip() for x in lines] #To remove unneccesary white spaces and "\n"

而不是在“\n”上拆分文件