为什么我的python脚本只写SELECT sql查询的最后一行

时间:2018-03-28 08:00:20

标签: python mysql parsing line

我有一个python代码,它从mysql数据库执行SELECT,然后将结果写入文件。 结果,files / tmp / ifcfg- *没问题,但在文件/ tmp / route中我只看到数据库查询的最后一行,它看起来像:

10.130.48.0/23 via 10.130.48.7

但我希望

10.130.48.0/23 via 10.130.48.7
192.168.156.0/22 via 192.168.156.91
10.16.234.0/29 via 10.16.234.2
10.16.234.8/29 via 10.16.234.10

是什么原因?

    get_settings = "SELECT id_srv, \
                       vlan, \
                       phys_dev_srv, \
                       onboot, \
                       inet_ntoa(subnet_ipv4), \
                       prefix, \
                       inet_ntoa(int_ipv4), \
                       inet_ntoa(dns_srv_01), \
                       inet_ntoa(dns_srv_02), \
                       dns_domain \
                       FROM interfaces_ipv4 WHERE id_srv = '%i'" % (curr_srv_id);
cursor = conn.cursor()
cursor.execute(get_settings)
rows = cursor.fetchall()
for row in rows:
    with open('/tmp/ifcfg-' + row[2] + '.' + str(row[1]), 'w+') as result, \
         open('/tmp/route', 'w+') as route:
        result.write('# vlan ' + str(row[1]) + '\n')
        result.write('VLAN=yes' + '\n')
        result.write('BOOTPROTO=static' + '\n')
        result.write('NAME=' + row[2] + '.' + str(row[1]) + '\n')
        result.write('DEVICE=' + row[2] + '.' + str(row[1]) + '\n')
        result.write('PHYSDEV=' + row[2] + '\n')
        result.write('ONBOOT=' + row[3] + '\n')
        result.write('IPADDR=' + row[6] + '\n')
        result.write('PREFIX=' + str(row[5]) + '\n')
        result.write('DNS1=' + row[7] + '\n')
        result.write('DNS2=' + row[8] + '\n')
        result.write('DOMAIN=' + row[9] + '\n')

        route.write(row[4] + '/' + str(row[5]) + ' via ' + row[6] +'\n')

1 个答案:

答案 0 :(得分:1)

for-loop语句放在cursor = conn.cursor() cursor.execute(get_settings) rows = cursor.fetchall() with open('/tmp/ifcfg-' + row[2] + '.' + str(row[1]), 'w+') as result, open('/tmp/route', 'w+') as route: for row in rows: result.write('# vlan ' + str(row[1]) + '\n') result.write('VLAN=yes' + '\n') result.write('BOOTPROTO=static' + '\n') result.write('NAME=' + row[2] + '.' + str(row[1]) + '\n') result.write('DEVICE=' + row[2] + '.' + str(row[1]) + '\n') result.write('PHYSDEV=' + row[2] + '\n') result.write('ONBOOT=' + row[3] + '\n') result.write('IPADDR=' + row[6] + '\n') result.write('PREFIX=' + str(row[5]) + '\n') result.write('DNS1=' + row[7] + '\n') result.write('DNS2=' + row[8] + '\n') result.write('DOMAIN=' + row[9] + '\n') route.write(row[4] + '/' + str(row[5]) + ' via ' + row[6] +'\n')

之外

<强>实施例

null

您的方法会覆盖文件的内容,因为您每次都在forloop中打开文件并再次编写内容。