我无法将以下代码的结果写入文件
import boto3
ACCESS_KEY= "XXX"
SECRET_KEY= "XXX"
regions = ['us-east-1','us-west-1','us-west-2','eu-west-1','sa-east-1','ap-southeast-1','ap-southeast-2','ap-northeast-1']
for region in regions:
client = boto3.client('ec2',aws_access_key_id=ACCESS_KEY,aws_secret_access_key=SECRET_KEY,region_name=region,)
addresses_dict = client.describe_addresses()
#f = open('/root/temps','w')
for eip_dict in addresses_dict['Addresses']:
with open('/root/temps', 'w') as f:
if 'PrivateIpAddress' in eip_dict:
print eip_dict['PublicIp']
f.write(eip_dict['PublicIp'])
这导致打印IP,但没有任何内容写入文件,打印结果为:
22.1.14.1
22.1.15.1
112.121.41.41
....
我只需要以这种格式编写内容
答案 0 :(得分:0)
for eip_dict in addresses_dict['Addresses']:
with open('/root/temps', 'w') as f:
if 'PrivateIpAddress' in eip_dict:
print eip_dict['PublicIp']
f.write(eip_dict['PublicIp'])
您正在重新打开文件,以便在循环的每次迭代中进行写入。也许最后一次迭代在其dict中没有带有'PrivateIpAddress'的成员,因此文件被打开,截断并留空。用这种方式写它:
with open('/root/temps', 'w') as f:
for eip_dict in addresses_dict['Addresses']:
if 'PrivateIpAddress' in eip_dict:
print eip_dict['PublicIp']
f.write(eip_dict['PublicIp'])
答案 1 :(得分:0)
以附加模式打开文件
.cgi
或 在循环外声明文件