2017-03-31 310 views
0

我有一個輸出IP列表的函數。Python - 爲循環輸出寫入文件

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

輸出通常看起來像 下面是CSDP_LAB_STAGING

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 

的IP地址現在我想寫這個輸出到文件。

我所做的是

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。我以爲我可能會搞砸這個縮進,但是這個幫助我。還有什麼我失蹤?

P.S.這是我的第一個Python腳本,所以如果我做了非常愚蠢的事情,請原諒我。

+2

這太過於複雜。一般來說,請閱讀關於'open'函數和文件對象的Python文檔(尤其是'write'方法)。 – ForceBru

+1

@ForceBru說什麼。這應該通過自己的「開放」來完成。但是如果你想忽略所有的警告,其他人都會直接給你sys.stdout .....只要把sys.stdout.flush()放在sys.stdout.close() – TehTris

回答

1

重新分配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() 
1

我甚至不知道最後一個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。我把所有的ips放在一個字符串中,以便保存在文件中。 的with塊不需要任何close功能

EDIT(我不能評論) 這兩種方法的區別在於:

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

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

僅在第一個,所有在文件之前那個函數調用是exe cuted將被刪除。隨着追加,它不會,和my_file.write(something_to_add)將被添加到文件的末尾。 但開業'w'模式將刪除該文件只有 我測試自己這個精確行的執行,這一點也適用「W」以及與「A」

0

我經歷了大家的響應上方,並試圖每一個出來。但是每個解決方案只會導致最後一個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() 
0
def convertHostNamesToIps(hostnames): 
ip = server.system.search.hostname(sessionKey, hostnames) 
iplist = [] # Make a temporal list. 
for ips in ip: 
    print (ips.get('ip')) # This only print your ips, it isn't necesary. 
    iplist.append(ips.get('ip')) # Add the current ip in the list. 
with open("test.txt","w") as txt: # Open the file but when you finish to use the file it will automatically close. 
    txt.writelines(iplist) 

我希望這會幫助你。