原始txt内容:
Connected to IP1
BIP1 PORT1 N/A
.1
BIP2 PORT2 N/A
.2
BIP3 PORT3 N/A
.3
Connected to IP2
2bip1 port1 N/A
.1
2bip2 port2 N/A
.2
2bip3 port3 N/A
.3
想要的结果txt内容:
Connected to IP1,BIP1,PORT1 N/A, .1
Connected to IP1,BIP2,PORT2 N/A, .2
Connected to IP1,BIP3,PORT3 N/A, .3
Connected to IP2,2bip1,port1 N/A, .1
Connected to IP2,2bip2,port2 N/A, .2
Connected to IP2,2bip3,port3 N/A, .3
将txt转成字典,让Connected to IP1和Connected to IP2成为键,bip行成为值。把bip行没两行,整合到一行。
最后没成功,求解答或思路,谢谢。
#Connected to IP1,BIP1,PORT1 N/A, .1
Connected = ''
ports = ''
point = ''
with open('test.txt' , 'r') as f1:
for one in f1.readlines():
one = one.replace('\n','')
if 'Connected' in one:
Connected = one
elif 'port' in one or 'PORT' in one:
ports = one
elif '.' in one:
point = one
else:
pass
with open('save.txt' , 'a') as f2:
if Connected !='' and ports!='' and point!='':
f2.write(Connected + ', ' + ports+ ', '+ point + '\n')
ports = ''
point = ''
with open('raw_data.txt', 'r') as fp:
contents = list()
lines = fp.readlines()
for i in range(0, len(lines), 8):
key = lines[i].strip()
for j in range(1, 7, 2):
print(lines[i+j])
a, b, c = lines[i+j].strip().split()
d = lines[i+j+1].strip()
contents.append('%s, %s, %s %s, %s'%(key, a, b, c, d))
with open('out_data.txt', 'w') as fp:
fp.write('\n'.join(contents))