2012-03-08 76 views
0

我目前使用此代碼的頂部部分是正確的,但我不能似乎將它保存到文件遇到問題將數據寫入到文件

這是我當前的代碼

for line in myfile: 
list_of_line = line.split() 
if 'Failed password for' in line: 
    ip_address_port = list_of_line[-4] 
    ip_address_list = ip_address_port.split(':') 
    ip_address = ip_address_list[0] 
    print '\'',ip_address,'\'' 
    if ips_desc.has_key(ip_address): 
     count_ip = ips_desc[ip_address] 
     count_ip + count_ip +1 
     ips_desc[ip_address] +=1 
     count_ip =0 
    else: 
     ips_desc[ip_address] = 1 

print ips_desc 

myfile = open('blacklist.txt','w') 
for ips_items in ips_desc.keys(): 
myfile.write(ips_items) 

但最後3行不工作任何想法?

+2

你會得到什麼錯誤信息? – 2012-03-08 17:25:22

+1

另外,它可能是堆棧溢出格式,但最後一行應該有一個縮進。 – 2012-03-08 17:26:04

+1

我認爲myfile.write是縮進了一個,否則這將是問題 – 2012-03-08 17:26:43

回答

2

在程序結尾處添加myfile.close(),或者刷新正在寫入的文件夾。因爲你沒有關閉它,它並不總是正確更新。 所以

for line in myfile: 
    list_of_line = line.split() 
    if 'Failed password for' in line: 
     ip_address_port = list_of_line[-4] 
     ip_address_list = ip_address_port.split(':') 
     ip_address = ip_address_list[0] 
     print '\'',ip_address,'\'' 
    if ips_desc.has_key(ip_address): 
     count_ip = ips_desc[ip_address] 
     count_ip + count_ip +1 
     ips_desc[ip_address] +=1 
     count_ip =0 
    else: 
     ips_desc[ip_address] = 1 

print ips_desc 

myfile = open('blacklist.txt','w') 
for ips_items in ips_desc.keys(): 
    myfile.write(ips_items) 
myfile.close() 
+0

工作如何我只說ip地址初始化,13次嘗試,如果ips_item> 13: – 2012-03-08 17:37:47

+0

ips_desc.keys()中的ips_items:如果ips_items> 13:myfile.write(ips_items) – 2012-03-08 17:40:05

+0

我得到這個,但它仍然把所有的IP地址在那裏,而不是隻有一個超過13嘗試。這裏的代碼MYFILE =開放( 'blacklist.txt', 'W') 知識產權在ips_desc.keys(): 如果ips_desc> 13: myfile.write(ips_items) myfile.close() – 2012-03-08 18:01:13

0

如果你打開一個文件爲只讀,在它(再次)給你寫之前必須關閉它。所以,你應該這樣做:

myfile.close() 
myfile = open('blacklist.txt','w') 
for ips_items in ips_desc.keys(): 
    myfile.write(ips_items) 
myfile.close() 

也許應該是:

myfile.writelines(ips_items) ? 
+0

.write()應該工作,因爲密鑰是ip-adresses(推測是),所以它應該只有一個字符串 – 2012-03-08 17:50:21

0

你的問題是你沒有關閉文件。

以前的答案很好,但我建議你在處理文件時使用with語句。因爲如此:

with open(file, 'w') as myfile: 
    myfile.write('something') 

這樣,當您退出with語句時文件關閉,您將永遠不會再遇到此問題。