从 while 循环中编写一个文本文件,其中的行有两个单词,用逗号分隔

Writing a text file with rows that have two words separated by comma from a while loop

dictionary = {}
name = input("Name: ")

while name: #while the name is not blank
    age = input("Age: ")
    dictionary[name] = age
    name = input("Name: ")

print("Thank you, bye!")

f = open("1ex.txt","w")
f.write( str(dictionary) )
f.close()

所以我有这段代码,它做我想做的事,但我似乎无法弄清楚如何编写文件,这样它就没有字典,而是像这样:

Jane, 25
Jim, 24

我尝试将所有内容都放入列表中,但对我来说行不通。

试试这个:

dictionary = {}
name = input("Name: ")

while name: #while the name is not blank
    age = input("Age: ")
    dictionary[name] = age
    name = input("Name: ")

print("Thank you, bye!")

# Open the file
with open("1ex.txt","w") as f:
    # For each key/value pair in the dictionary:
    for k, v in dictionary.items():
        # Write the required string and a newline character
        f.write(f"{k}, {v}\n")