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

Time:08-27

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)

CodePudding user response:

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])))
    
  • Related