[Tutor] Writing a dictionary to txt file

Alan Gauld alan.gauld at yahoo.co.uk
Sun Aug 30 03:57:37 EDT 2020


On 30/08/2020 04:28, nzbz xx wrote:
> The original txt file is written in this format:
> 
> Plant 1
> date & time
> description
> description
> description
> (Blank line)
> Plant 2
> ...
> ....
> ...
> 
> I have converted this file into dict = {'Plant 1':
> ['datetime','description','description','description'], 'Plant2' :
> ['datetime',....]}. So how can i write this dict back to the txt file in
> the same format?

It looks like you need two loops: an outer one to read the dictionary
keys and an inner one to process the list of value items

for key in thedict:
    write key to file
    for item in thedict[key]:
        write item
    write blank line

If it needs to go back in "the same" file then the normal
approach would be to

read the data from the file
rename the file file.old or similar
write the data to a new file with the original name
if successful delete the .old version
else delete the new file and rename .old back to the original.


-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list