从 excel 中提取的过滤 IP 文件

Filter IP File extracted from excel

我有一个从 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
---