Create multiple text files with distinct names from dictionary keys

Question:

I’m trying to create multiple text files from each key in a dictionary.

I have made several unsuccessful attempts. The result is that the files are produced correctly, but only the last key (Signal 8) is being written to every file. I don’t know where I’m messing up.

signals_dict = {'Signal 1': 1, 
                'Signal 2': 1, 
                'Signal 3': 1, 
                'Signal 4': 1, 
                'Signal 5': 1, 
                'Signal 6': 1, 
                'Signal 7': 1, 
                'Signal 8': 1}


def to_string():
    count = 0
    while count <= len(signals_dict):
        count +=1
        for keys,values in signals_dict.items():
            with open(f'signal{count}.txt','w') as wf:
                wf.write(keys)

to_string()

Output:

enter image description here

enter image description here

Asked By: CUI

||

Answers:

Are you just after a unique file name (based on the key) that contains the value? If so:

for name, value in signals_dict.items():
  with open(f"{name}.txt", "w") as fh:
    fh.write(str(value))
Answered By: g.d.d.c
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.