我有一個從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
簡而言之,它不起作用,我找不到原因
uj5u.com熱心網友回復:
正如評論中所討論的,如果您的代碼“失去控制”,這僅僅意味著您的輸入資料不像您想象的那么干凈 - 您需要在處理之前或在此腳本中對其進行清理。
此外,您的處理可能要簡單得多。這對我有用(但顯然還需要一些驗證,以及洗掉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
---
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/476882.html
