Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 
like image 371
Stefan Avatar asked Mar 02 '12 16:03

Stefan


People also ask

How do you save a file in Python?

Right-click the Python window and select Save As to save your code either as a Python file (. py) or Text file (. txt). If saving to a Python file, only the Python code will be saved.

How do you save data to a text file in Python?

To write to a text file in Python, you follow these steps: First, open the text file for writing (or append) using the open() function. Second, write to the text file using the write() or writelines() method. Third, close the file using the close() method.


1 Answers

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') 
like image 52
warvariuc Avatar answered Sep 21 '22 23:09

warvariuc