python配置模板性能改进

时间:2016-03-14 13:52:06

标签: python python-3.x

我是python的新手,并创建了我的第一个配置Generatign脚本。它读取一个txt模板查找我设置的变量,然后根据我所有位置的excel csv创建模板。

它有效,但我只是寻找最有效的方法来做这个作为我下一个脚本的学习曲线。



import csv
import os
with open('Data/ShowroomData.csv', 'rt') as Data:
    SR = csv.DictReader(Data, delimiter=',', quotechar='|')
    for row in SR:
        # if you were to print just `row`, you would get a dictionary

        # set config file path
        folder  = 'Data/'
        filename = row['Host'].strip()
        path = folder + '/' + row['Location'].strip()
        R1file = path + '/STR-' + filename + '-RTR-01.txt'
        # check if path exists if not make path
        if not os.path.exists(path):
            os.makedirs (path)
        # Read in the config file
        R1 = None
        with open('Data/STR-RTR-01.txt', 'r') as R1Template, open(R1file, 'w') as configfile:
            R1 = R1Template.read()

            # Replace the target string
            R1 = R1.replace('$STR', row['Host'].strip())
            R1 = R1.replace('$IP', row['Subnet'])
            R1 = R1.replace('$DMVPN-DSL', row['DMVPN-DSL'])
            R1 = R1.replace('$DMVPN-4G', row['DMVPN-4G'])
            R1 = R1.replace('$BGPASNO', row['BGPAS'])
            R1 = R1.replace('$KCIP', row['KCIP'])
            R1 = R1.replace('$WRIP', row['WRIP'])
            R1 = R1.replace('$LOIP', row['Loopback'])              
            R1 = R1.replace('$DSL-USER', row['DSL-USER'])
            R1 = R1.replace('$DSL-PASS', row['DSL-PASS'])
            R1 = R1.replace('$Location', row['Location'].strip())
            R1 = R1.replace('$Date', row['InstallDate'])

            # check if the BT column is empty
            if row['BT'] == (''):
                for line in R1.split('\n'):
                    if '$BTSUB' not in line:
                        # Write file without BT static routes
                        configfile.write("{}\n".format(line))
            else:
                R1 = R1.replace('$BTSUB', row['BT'])
                # Write the file 
                configfile.write(R1)

print('Config templates are now complete!')




1 个答案:

答案 0 :(得分:1)

您的代码大多看起来很好。至于提示有几个:

  1. 避免使用+来连接字符串。首选字符串格式 例如:'/STR-{}-RTR-01.txt'.format(filename) 这具有易于阅读以及避免过多的内存分配和复制的优点。由于python中的字符串是不可变的,因此每次使用+都会生成一个新的字符串实例。
  2. 使用os.path.join加入路径时。此方法使事物更明确,处理分隔符并避免字符串连接。
  3. 在您的脚本环境中,上述建议不会对执行时间或内存使用产生很大影响,这些可以帮助大型应用程序。

    最后,不要使用“string.replace”来实现你的模板,看看Jinja2。 Jinja 2是一个模板引擎,可以很容易地配置为生成几乎任何类型的基于文本的输出(我已经多次使用它进行代码生成)。