无法将数据写入文件

时间:2012-03-08 17:24:30

标签: python

我目前正在使用此代码,顶部是正确的,但我似乎无法将其保存到文件

这是我目前的代码

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行没有任何想法?

3 个答案:

答案 0 :(得分: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()

答案 1 :(得分: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) ?

答案 2 :(得分:0)

您的问题是您没有关闭文件。

之前的答案很好,但我建议您在处理文件时使用with语句。如此:

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

这样退出with语句时文件就会关闭,你再也不会遇到这个问题了。