您好我正在阅读以下格式的文件data.txt。
Last table change time : 69 days, 0:17:19 ago
Number of table inserts : 93
Number of table deletes : 87
Number of table drops : 0
Number of table age-outs : 0
Port Neighbor Device ID Neighbor Port ID TTL
Et2/1 CN-Arista2 Ethernet5/1 120
Et2/2 CN-Arista2 Ethernet5/2 120
Et2/3 CN-Arista3 Ethernet5/3 120
Et2/4 CN-Arista Ethernet5/4 120
Et64/1 CN-Spine2 Ethernet64/1 120
Ma1 Arista01.Dmech.rack01 Ethernet1 120
我需要输出如下
Et2/1, CN-Arista2, Ethernet5/1
Et2/2, CN-Arista2, Ethernet5/2
Et2/3, CN-Arista3, Ethernet5/3
Et2/4, CN-Arista, Ethernet5/4
Et64/1, CN-Spine2, Ethernet64/1
Ma1, Arista01.Dmech.rack01, Ethernet1
答案 0 :(得分:1)
我不确定你要做什么,但也许这会让你朝着正确的方向前进:
filename = 'myfile.txt'
with open(filename, 'r') as file:
for line in file:
print(*line.split(), sep=', ')
file.close()
谢谢TigerhawkT3:)
答案 1 :(得分:1)
试试这个:
fi = open('data.txt')
fo = open('data.csv')
for line in fi:
L = line.split()
S = ' '.join(L[5:8]).replace(',','') +', ' + ', '.join(L[14: : 6]) + '\n'
fo.write(S)
fo.close()
fi.close()
答案 2 :(得分:1)
input = """Port Neighbor Device ID Neighbor Port ID TTL
Et2/1 CN-Arista2 Ethernet5/1 120
Et2/2 CN-Arista2 Ethernet5/2 120
Et2/3 CN-Arista3 Ethernet5/3 120
Et2/4 CN-Arista Ethernet5/4 120
Et64/1 CN-Spine2 Ethernet64/1 120
Ma1 Arista01.Dmech.rack01 Ethernet1 120
"""
#create a test file
fn_in = "./testin.txt"
fn_out = "./testout.txt"
with open(fn_in, "w") as fo:
fo.write(input)
with open(fn_in, "r") as fi, open(fn_out,"w") as fo:
#drop first line
for line in fi.readlines()[1:]:
#split without argument treats consecutive spaces as 1 separator
#drop last field
fields = line.split()[:-1]
fo.write(", ".join(fields)+"\n")
有效吗?
$ cat testout.txt
Et2/1, CN-Arista2, Ethernet5/1
Et2/2, CN-Arista2, Ethernet5/2
Et2/3, CN-Arista3, Ethernet5/3
Et2/4, CN-Arista, Ethernet5/4
Et64/1, CN-Spine2, Ethernet64/1
Ma1, Arista01.Dmech.rack01, Ethernet1
答案 3 :(得分:0)
谢谢大家的回复。以下是符合我要求的最终代码。
fn_in = "data.txt"
with open(fn_in, "r") as fi:
#drop first 7 lines
for line in fi.readlines()[7:]:
#split without argument treats consecutive spaces as 1 separator
#drop last field
fields = line.split()[:-1]
if fields:
print(", ".join(fields))