我有一个像这样从excel中提取的文件:
"IP1
IP2
IP3"
IP4
"IP5
IP6"
在Excel中是这样的:
1号线:
IP1
IP2
IP3
2行:
IP4
第3行:
IP5
IP6
然后我写了一个python脚本:
c=0 #count " character to add the --- line in order to seperate the excel lines
lis=0 #listening mode, if 1 then we are inbetween "IP,.......", if 0 we have a line that contains exactly one IP
lines=[] #store data
with open("dest_ips", "r") as file:
for line in file:
if "0/24" in line:
continue
if '"' in line:
c+=1
lis=1
lines.append(line.replace('"',""))
if lis==0:
lines.append("---n") #add --- if there is just on IP per line, case handling for the if c==2 below
if c==2:
lines.append("---n")
c=0
lis=0
with open("result_test_ips","w") as file:
for i in lines:
file.write(i)
解释:我希望ip像这样列出:
IP1
IP2
Ip3
---
IP4
---
IP5
IP6
这在开始的几行中工作得很好,但过了一段时间,它失去了控制,我期望的行看起来像这样:
IP10
---
IP11
IP12
---
IP13
看起来像这样:
IP10
IP11
---
IP12
---
IP13
所以简而言之,它不起作用,我不知道为什么
正如在注释中所讨论的,如果您的代码"失去控制";这仅仅意味着您的输入数据并不像您想象的那么干净—您需要在处理之前或在此脚本中对其进行消毒。
同样,您的处理可以简单得多。这对我很有效(但显然需要一些验证仍然添加,以及剥离0/24
条目):
lines=[] #store data
with open("dest_ips", "r") as infile:
with open("result_test_ips","w") as outfile:
for line in infile:
if line.strip().startswith('"'):
outfile.write("---n")
outfile.write(line.replace('"',''))
elif line.strip().endswith('"'):
outfile.write(line.replace('"',''))
outfile.write("---n")
else:
outfile.write(line)
dest_ips
"192.168.1.1
192.168.1.1
192.168.1.1
192.168.1.1"
192.168.1.2
192.168.1.3
"192.168.1.4
192.168.1.4
192.168.1.4
192.168.1.4"
result_test_ips
---
192.168.1.1
192.168.1.1
192.168.1.1
192.168.1.1
---
192.168.1.2
192.168.1.3
---
192.168.1.4
192.168.1.4
192.168.1.4
192.168.1.4
---