Python Save to file

Python Save to file

file = open(Failed.py, w)
file.write(whatever)
file.close()

Here is a more pythonic version, which automatically closes the file, even if there was an exception in the wrapped block:

with open(Failed.py, w) as file:
    file.write(whatever)

You need to open the file again using open(), but this time passing w to indicate that you want to write to the file. I would also recommend using with to ensure that the file will be closed when you are finished writing to it.

with open(Failed.txt, w) as f:
    for ip in [k for k, v in ips.iteritems() if v >=5]:
        f.write(ip)

Naturally you may want to include newlines or other formatting in your output, but the basics are as above.

The same issue with closing your file applies to the reading code. That should look like this:

ips = {}
with open(today,r) as myFile:
    for line in myFile:
        parts = line.split( )
        if parts[1] == Failure:
            if parts[0] in ips:
                ips[pars[0]] += 1
            else:
                ips[parts[0]] = 0

Python Save to file

You can use this function:

def saveListToFile(listname, pathtosave):
    file1 = open(pathtosave,w) 
    for i in listname:
        file1.writelines({}n.format(i))    
    file1.close() 

# to save:
saveListToFile(list, path)

Leave a Reply

Your email address will not be published.