我在让 if 语句正常工作时遇到了一些麻烦。在 iplist.txt 的末尾有一个我不想运行的空行,但由于某种原因,它仍在运行。我尝试删除文件的最后一行,但它只删除最后一个合法行而不是空行,我什至尝试删除空格、空行和空行,但它仍然会与一行一起运行。最奇怪的部分是空白在 if 块和 else 块中都运行。 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.3810.9.10.4510.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)
1 回答
繁花如伊
TA贡献2012条经验 获得超12个赞
Python 有一种方法可以读取单独的行。尝试
lines = file.readlines()
lines = [x.strip() for x in lines] #To remove unneccesary white spaces and "\n"
而不是在“\n”上拆分文件
添加回答
举报
0/150
提交
取消