I have a file extracted from excel like this:
"IP1
IP2
IP3"
IP4
"IP5
IP6"
In Excel it looks like this:
Line 1:
IP1
IP2
IP3
Line 2:
IP4
Line 3:
IP5
IP6
I then wrote a python script:
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)
Explanation: I want the IPs to be listed like this:
IP1
IP2
Ip3
---
IP4
---
IP5
IP6
And this works just fine for the first few, but after some time it looses control and lines that i expect to look like this:
IP10
---
IP11
IP12
---
IP13
Look like this:
IP10
IP11
---
IP12
---
IP13
So in short, it does not work and I cannot find why
CodePudding user response:
As discussed in the comments, if your code is "losing control" that simply means that your input data is not as clean as you thought - you need to sanitize it, either before processing, or in this script.
Also, your processing could be far simpler. This works for me
(but obviously needs some validation still adding, as well as stripping out the 0/24
entries):
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
---