Python Save to file
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
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
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)
In order to write into a file in Python, we need to open it in write w
, append a
or exclusive creation x
mode.
We need to be careful with the w
mode, as it will overwrite into the file if it already exists. Due to this, all the previous data are erased.
Writing a string or sequence of bytes (for binary files) is done using the write() method. This method returns the number of characters written to the file.
with open('Failed.py','w',encoding = 'utf-8') as f:
f.write("Write what you want to write in\n")
f.write("this file\n\n")
This program will create a new file named Failed.py
in the current directory if it does not exist. If it does exist, it is overwritten.
We must include the newline characters ourselves to distinguish the different lines.