Reputation: 107
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?
Upvotes: 1
Views: 1584
Reputation: 2310
def save(diction):
with open('save.txt', 'w') as savefile:
for key, value in diction.items():
savefile.write(str(key)+ ' ' + str(value) + '\n')
Upvotes: 0
Reputation: 365717
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.
Upvotes: 1
Reputation: 264
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)
Upvotes: 0
Reputation: 50185
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)
Upvotes: 1