Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

I need help in converting a dictionary to plaintext and then writing this data to a text file

I’m making a program that saves user data into a text file.
Currently I’m using a dictionary to be referenced throughout the entire program, and when the user quits the program, it takes all the data from the dictionary and writes it into the text file. While I have most of the program working, I’m having a bit of trouble writing the actual end data into the text file. If you could help me, I would appreciate it alot!

I’m also quite new to programming as a whole so sorry if any of my coding habits are bad.

lis = []
for new_k, new_v in dictionary.items():
    lis.append([new_k, new_v])
            
    output = (" ".join(map(str, lis)))
    acc = open("Storage.txt", "w")
    acc.write(lis)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

This is an example of how you can open the file and write a string to it

dictionary = {"a": 1, "b": 2}

lis = []

with open("Storage.txt", "w") as acc:
    for new_k, new_v in dictionary.items():
        lis.append([new_k, new_v])
                
        output = (" ".join(map(str, lis)))
        acc.write(output)

However, this code does not behave well as it writes the same data in each iteration of the for loop, which is why I recommend you instead move the file I/O after you have created your list like so

dictionary = {"a": 1, "b": 2}

lis = []


for new_k, new_v in dictionary.items():
    lis.append([new_k, new_v])

with open("Storage.txt", "w") as acc:               
    for sublist in lis:
        acc.write('{}, {}\n'.format(str(sublist[0]), str(sublist[1])))
    
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading