124

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
3
  • 2
    Out of pure curiosity: is there a way to turn one answer into the accepted one? (Stefan seems to be inactive for years) Commented Apr 6, 2016 at 9:37
  • What is the actual problem? Commented Jun 10, 2020 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. Commented Jun 24, 2021 at 16:38

5 Answers 5

249
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')
Sign up to request clarification or add additional context in comments.

6 Comments

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.
It's not about coding style. file is built-in function as many others. It's not recommended to shadow these built-in functions with other variables.
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...
@Anatoly you are not closing the file
@warvariuc thank you, you're right, then this doesn't seem like a best practice
|
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

Comments

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.

Comments

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)

1 Comment

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.
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.

3 Comments

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 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.
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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.