Python-Write for循环输出到fi

2024-05-21 00:13:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个输出IP列表的函数。

def convertHostNamesToIps(hostnames):
    ip = server.system.search.hostname(sessionKey, hostnames )
    for ips in ip:
        print (ips.get('ip'))

输出通常看起来像 以下是CSDP_LAB_STAGING的IP

172.29.219.123
172.29.225.5
172.29.240.174
172.29.225.46
172.29.240.171
172.29.240.175
172.29.219.119
172.29.219.117
172.29.219.33
172.29.219.35
.
.
.
172.29.219.40
172.29.219.35
172.29.219.40
172.29.219.118
172.29.219.121
172.29.219.115
172.29.225.51

现在我想把这个输出写入文件。

我所做的是

def convertHostNamesToIps(hostnames):
    ip = server.system.search.hostname(sessionKey, hostnames )
    sys.stdout=open("test.txt","w")
    for ips in ip:
        print (ips.get('ip'))
    sys.stdout.close()

但上面的代码只将最后一个IP写到test.txt。我想我可能弄乱了凹痕,但那件事帮助了我。我还缺什么吗?

这是我有史以来第一个python脚本,所以请原谅我做了一些非常愚蠢的事情。


Tags: inipforsearchgetserverdefsystem
3条回答

我仔细检查了上面每个人的回答,并尝试了每一个。但每种解决方案都只导致最后一个IP被打印到文件中。阅读documentation使我得出结论,我需要附加到文件,而不是写入文件。

def convertHostNamesToIps(hostnames):
    ip = server.system.search.hostname(sessionKey, hostnames )
    my_file=open("test.txt","a")
    for ips in ip:
        my_file.write(ips.get('ip')+'\n')
    my_file.close() 

我甚至不知道最后一个IP是如何保存的,因为您的函数中没有任何write。 你可以试试这个:

def convertHostNamesToIps(hostnames):
    ip = server.system.search.hostname(sessionKey, hostnames )
    list_ips = str ()
    for ips in ip:
    list_ips = list_ips + ips.get('ip') + '\n'

with open ('test.txt', 'w') as file:
    file.write (list_ips)

你需要像file.write ()这样的东西来保存你的ips。我把所有的IP放在一个字符串中,这样它们就更容易保存在文件中。 with块不需要任何^{函数

编辑(我无可奉告) 这两种方法的区别:

my_file = open ('test.txt', 'w')

以及

my_file = open ('test.txt', 'a')

只是在第一个函数中,在执行函数调用之前文件中的所有内容都将被删除。如果使用append,则不会,并且my_file.write(something_to_add)将添加到文件末尾。 但是在'w'模式下打开文件时,只会在执行这一行时删除文件 我测试过自己,这对“w”和“a”都有效

重新分配sys.stdout?那是。。。勇敢的。

可以将打开的文件分配给其他变量,然后调用其write方法。如果你想在不同的行上写东西,你必须自己添加。

def convertHostNamesToIps(hostnames):
    ip = server.system.search.hostname(sessionKey, hostnames )
    my_file=open("test.txt","w")
    for ips in ip:
        my_file.write(ips.get('ip')+'\n')
    my_file.close()

相关问题 更多 >