我有一个python代码,它从mysql数据库中进行选择,然后将结果写入文件。 结果,files/tmp/ifcfg-*是可以的,但在file/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')
将
with
语句置于for-loop
之外Ex:
您的方法是重写文件的内容,因为您每次都在forloop中打开文件并再次写入内容
相关问题 更多 >
编程相关推荐