112

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
Eric Leschinski
  • 146,994
  • 96
  • 417
  • 335
Stefan
  • 1,233
  • 2
  • 8
  • 9
  • 2
    Out of pure curiosity: is there a way to turn one answer into the accepted one? (Stefan seems to be inactive for years) – Wolf Apr 06 '16 at 09:37
  • What is the actual problem? – user207421 Jun 10 '20 at 10:11
  • 5
    @Wolf no, and that's on purpose. The meaning of the checkmark isn't "this is the one and only truth", it is "this is the answer which made the OP happy". And having questions with good answers but without a checkmark doesn't reduce their usefulness. – rumtscho Jun 24 '21 at 16:38

5 Answers5

230
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')
warvariuc
  • 57,116
  • 41
  • 173
  • 227
  • 2
    `file` is not a protected word in python, there's no need to use `file_`, unless your coding style guide requires the `_` suffix on variables in whatever context (file, function, class, method) this takes place in. – zstewart Sep 21 '15 at 05:33
  • 7
    It's not about coding style. `file` is built-in function as [many others](https://docs.python.org/2/library/functions.html). It's [not recommended](http://stackoverflow.com/questions/9109333/is-it-bad-practice-to-use-a-built-in-function-name-as-an-attribute-or-method-ide) to shadow these built-in functions with other variables. – warvariuc Sep 21 '15 at 08:17
  • 1
    `file` was deprecated and removed in python 3, so it's perfectly ok to use there. I didn't see the 2.7 tag on the question, and I usually use python 3... – zstewart Sep 21 '15 at 15:31
  • 1
    I love one-liners in such cases: `open('Failed.py', 'w').write('whatever')` – Anatoly Vasilyev Feb 14 '17 at 09:55
  • 2
    @Anatoly you are not closing the file – warvariuc Feb 14 '17 at 13:10
  • 3
    @warvariuc thank you, you're right, then this doesn't seem like a best practice – Anatoly Vasilyev Feb 14 '17 at 13:39
23

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
David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490
3

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.

MRUNAL MUNOT
  • 395
  • 1
  • 5
  • 18
2

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)
fcdt
  • 2,371
  • 5
  • 14
  • 26
  • I think adding an exception handler would be a good idea. this would crash when the file does not exist, disk full, format error, etc. – Hacky Dec 30 '22 at 01:39
1
myFile = open('today','r')

ips = {}

for line in myFile:
    parts = line.split()
    if parts[1] == 'Failure':
        ips.setdefault(parts[0], 0)
        ips[parts[0]] += 1

of = open('failed.py', 'w')
for ip in [k for k, v in ips.iteritems() if v >=5]:
    of.write(k+'\n')

Check out setdefault, it makes the code a little more legible. Then you dump your data with the file object's write method.

jaime
  • 2,234
  • 1
  • 19
  • 22
  • 1
    Exactly, what he said. Append an of.close to the end there. Otherwise you're assuming the GC will close the file. Explicit is better than implicit. Thanks. – jaime Mar 02 '12 at 17:11
  • 1
    @jaime Really you need to do more than just call `close`. You need to do it in a finally block to defend against exceptions. The idiomatic way is to use a `with` context handler. – David Heffernan Mar 02 '12 at 17:28
  • 1
    Yeah thanks. That crossed my mind, but I was worried about explaining when finally gets called. Then after reading your comment I realized he tagged the question python-2.7. Thanks. – jaime Mar 02 '12 at 18:22