2017-08-04 55 views
0

我有一个文本文件是交换机接口配置。我想从配置中拉出几行并将它们输出到csv。任何帮助,将不胜感激输出网络交换机配置txt到csv多列

我的代码下面输出每个字母到自己的专栏。 CSV的图片后运行:使用http://i.imgur.com/hmndZwQ.png

import csv 
import sys 

txt_file = r"results.txt" 
csv_file = r"testBook.csv" 

csv_out = open(csv_file, "w") 

in_txt = open(txt_file, "r") 

out_csv = csv.writer(csv_out) 


arr = [] 

for line in in_txt: 
    arr.append(line) 


out_csv.writerows(arr) 




csv_out.close() 

文本文件:

文件名:172.16.0.11.txt

interface 0/1 traffic-shape 5 description 'testname' switchport mode trunk switchport trunk native vlan 20 switchport trunk allowed vlan 2-3,20,52 ip access-group mbps25 in 1 exit interface 0/2 description 'testname5' switchport mode trunk exit interface 0/3 speed 1000 full-duplex switchport mode access switchport access vlan 2 exit

我想获得的东西接近输出此:http://i.imgur.com/1lb9R6D.png

细分:

交换机的IP列会从文件名172.16.0.11.txt

界面柱会从接口数量

描述列会从填充填充填充接口的信息(如果它有说明)

交通形柱会从该填充接口的信息(如果它有一个交通形)

IP接入组列将来自填充接口的信息(如果它有一个存取的基团)

+0

你应该先显示你所尝试过的。目前这是一个*给我的代码*问题,这是不是很好的收到在这个网站上。请阅读[问]知道如何改进它。 –

回答

0

问题:...拔出从配置,并将其输出的几行到CSV

#     keyword : (fieldname, from, to) 
D = OrderedDict([('_', ('Switch IP',)), 
       ('interface',('Interface', 1, 2)), 
       ('description', ('Description', 1, 2)), 
       ('traffic-shape', ('Traffic-Shape', 1, 2)), 
       ('ip', ('IP Access-Group', 2, 5))]) 

with open(filename + ".txt") as txt_file, open('testBook.csv', 'w') as csv_file: 
    # Build Fieldnames from D 
    fieldnames = [D[d][0] for d in D] 
    writer = csv.DictWriter(csv_file, fieldnames=fieldnames) 
    writer.writeheader() 

    # Init CSV Record 
    record = {fieldnames[0]: filename} 

    while True: 
     line = txt_file.readline()[:-1] 
     if not line: break 

     words = line.split() 

     # Write CSV Record if 'exit' 
     if words[0] == 'exit': 
      writer.writerow(record) 
      record = {fieldnames[0]:filename} 
     else: 
      try: 
       # Get Keyword Setting from D 
       k = D[words[0]] 
       # Update CSV Record 'fieldname' with Slice(from,to) 
       record[k[0]] = ' '.join(words[k[1]:k[2]]) 
      except: 
       pass 

输出

Switch IP,Interface,Description,Traffic-Shape,IP Access-Group 
172.16.0.11,0/1,'testname',5,mbps25 in 1 
172.16.0.11,0/2,'testname5',, 
172.16.0.11,0/3,,, 

用Python测试:3.4.2

+0

解决方案工作,谢谢! – glwallum