输出网络交换机配置txt到csv多列

时间:2017-08-04 13:24:17

标签: python csv

我有一个文本文件,即交换机接口配置。我想从配置中拉出几行并将它们输出到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

故障:

Switch IP列将填充文件名172.16.0.11.txt

接口列将填充接口编号

描述列将从该接口信息填充(如果它有描述)

流量形状列将从该接口信息填充(如果它具有流量形状)

ip access-group列将从该接口信息填充(如果它具有访问组)

1 个答案:

答案 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