Python Save to file

Stefan picture Stefan · Mar 2, 2012 · Viewed 330.9k times · Source

I would like to save a string to a file with a python program named Failed.py

Here is what I have so far:

myFile = open('today','r')

ips = {}

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

for ip in [k for k, v in ips.iteritems() if v >=5]:
    #write to file called Failed.py

Answer

warvariuc picture warvariuc · Mar 2, 2012
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')