1

I'm trying to take a dictionary and write it to a file. Each line of output is suppose to contained the key and its value separated by a single space. So far I have the following:

def save(diction):

    savefile = open("save.txt", "w")

    for line in diction:
        values = line.split()
        savefile.write(values)
    savefile.close()

I'm not sure if this is writing to the file or if it even saves the file with the .close() function. Any advice?

2
  • Any reason not to use pickle? wiki.python.org/moin/UsingPickle Commented Nov 19, 2013 at 20:56
  • Note that savefile.write does not write a NL or CR character to your file, so you probably want to to that if it isn't in your values. Commented Nov 19, 2013 at 20:57

4 Answers 4

1

The values are being written to the file on savefile.write(values), however the method with which you are opening and closing the file is a bit dangerous. If you encounter an error the file may never be closed. It's better to use with to ensure that the file will automatically be closed when leaving the with block, whether by normal execution or on error. Also, you probably mean to iterate through diction.items()?

def save(diction):
    with open("save.txt", "w") as savefile:
        for key, value in diction.items():
            values = "%s %s\n" % (key, value)
            savefile.write(values)
Sign up to request clarification or add additional context in comments.

4 Comments

No, the values aren't being written to the file, because values is the result of line.split(), which is a list, not a str.
@abarnert Good point. In any case, the provided solution solves that problem.
Well, yes, but each of his values is the result of calling split on each line in an iterable of lines; each of your values is generated from each key-value pair from a dictionary. So it's not even remotely the same code.
@abarnert uhhhh OP: "Each line of output is suppose to contained the key and its value separated by a single space."
1

If you try to call this function, it will give you an exception, like this:

----> 7         savefile.write(values)

TypeError: must be str, not list

… and then quit. So no, it's not writing anything, because there's an error in your code.

What does that error mean? Well, obviously something in that line is a list when it should be a str. It's not savefile, it's not write, so it must be values. And in fact, values is a list, because that's what you get back from split. (If it isn't obvious to you, add some debugging code into the function to print(values), or print(type(values)) and run your code again.)

If you look up the write method in the built-in help or on the web, or re-read the tutorial section Methods of File Objects, you will see that it does in fact require a string.

So, how do you write out a list?

You have to decide what you want it to look like. If you want it to look the same as it does in the print statement, you can just call str to get that:

savefile.write(str(values))

But usually, you want it to be something that looks nice to humans, or something that's easy to parse for later scripts you write.

For example, if you want to print out each values as a line made up of 20-character-wide columns, you could do something like this:

savefile.write(''.join(format(value, '<20') for value in values) + '\n')

If you want something you can parse later, it's usually better to use one of the modules that knows how to write (and read) specific formats—csv, json, pickle, etc.

The tutorial chapter on Input and Output is worth reading for more information.

Comments

0
def save_dict(my_dict):
    with open('save.txt', 'w') as f:
        for key in my_dict.keys():
            f.write(key + ' ' + my_dict[key] + '\n')

if __name__ == "__main__":
    my_dict = {'a': '1',
            'b': '2'}
    save_dict(my_dict)

1 Comment

Will this create a file named save.txt or do I have to create this file either by hand or using code?
0
def save(diction):
with open('save.txt', 'w') as savefile:
    for key, value in diction.items():
        savefile.write(str(key)+ ' ' + str(value) + '\n')

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.