简体   繁体   中英

Having trouble writing data to a file

i am currently using this code the top part is right but i cant seem to save it to file

this my current code

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)

but last 3 lines dont work any ideas?

Add myfile.close() at the end of your program, or refresh the folder that you are writing to. Because you don't close it, it doesn't always update correctly. so

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()

If you open a file as read only, to write in it (again) you must close it before. So you should do this:

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

And maybe it should be:

myfile.writelines(ips_items) ?

Your problem is you didn't close the file.

The previous answer is good but I would suggest that you use the with statement when dealing with files. As so :

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

This way the file is close when you exit the with statement and you'll never have this problem again.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM