我有一個文本文件,我試圖從中提取列和數據。以下是數據的一個樣本:使用python將字段添加到文本文件中的列
-Global stats enabled
Cpu Utilization : 0.1 % 45.4 Gb/core
Platform_factor : 1.0
Total-Tx : 270.75 Mbps
Total-Rx : 0.00 bps
Total-PPS : 37.98 Kpps
Total-CPS : 0.00 cps
Expected-PPS : 102.71 Kpps
Expected-CPS : 2.78 Kcps
Expected-BPS : 764.51 Mbps
Active-flows : 366 Clients : 252 Socket-util : 0.0023 %
Open-flows : 2792 Servers : 65534 Socket : 366 Socket/Clients : 1.5
drop-rate : 270.75 Mbps
current time : 7.6 sec
test duration : 3592.4 sec
-Latency stats enabled
Cpu Utilization : 0.0 %
if| tx_ok , rx_ok , rx check ,error, latency (usec) , Jitter max window
| , , , , average , max , (usec)
----------------------------------------------------------------------------------------------------------------
0 | 1116, 0, 0, 0, 0 , 0, 0 | 0 0 0 0 0 0 0 0 0 0 0 0 0
1 | 1116, 0, 0, 0, 0 , 0, 0 | 0 0 0 0 0 0 0 0 0 0 0 0 0
2 | 1116, 0, 0, 0, 0 , 0, 0 | 0 0 0 0 0 0 0 0 0 0 0 0 0
3 | 1116, 0, 0, 0, 0 , 0, 0 | 0 0 0 0 0 0 0 0 0 0 0 0 0
[2J[2H
-Per port stats table
ports | 0 | 1 | 2 | 3
-----------------------------------------------------------------------------------------
opackets | 30391 | 48748 | 30360 | 48696
obytes | 2468147 | 68386300 | 2465677 | 68310324
ipackets | 0 | 0 | 0 | 0
ibytes | 0 | 0 | 0 | 0
ierrors | 0 | 0 | 0 | 0
oerrors | 0 | 0 | 0 | 0
Tx Bw | 4.77 Mbps | 130.69 Mbps | 4.76 Mbps | 130.53 Mbps
我需要創建項目等共計-TX,下降率等列...然後對這些每次迭代添加值,進入一個新的行。
目前我可以提取列,不過需要幫助的相關數據的行添加到CSV文件:
import csv
import itertools
with open('output.txt', 'r') as in_file:
stripped = (line.strip() for line in in_file)
lines = (line for line in stripped if line)
grouped = itertools.izip(*[lines] * 4)
with open('output_stats.csv', 'w') as out_file:
writer = csv.writer(out_file)
writer.writerow(('current time', 'drop-rate', 'Total-Tx', 'Total-Rx'))
writer.writerows(grouped)
是的,在這一點上,我只需要存儲包含':' 的行的條目,這樣我就可以使用'split(:)'謝謝你,會試試這個 –