在方括号 {} 内的 Python 中附加到文本文件中的字典

Appending to dictionary in text file in Python inside the brackers {}

我正在尝试将消息连同名称附加到文本文件中的空字典中。

def tweeting():
    f = open('bericht.txt', 'a')
    message = input('Put in message:  ')
    name = input('Put in your name: ')
    if name == '':
        name = 'Anonymous'
    tweet = name + '; ' + message
    f.write(tweet)
    f.close()
tweeting()

我得到的结果是这样的:

Tweets = {

}David; Hello everyone

消息位于括号 {} 之后。有没有办法将消息放在括号 {} 内? 感谢您的帮助。

您没有输入任何括号。只需添加括号如下-

def tweeting():
    f = open('bericht.txt', 'a')
    message = input('Put in message:  ')
    name = input('Put in your name: ')
    if name == '':
        name = 'Anonymous'
    tweet = '{' + name + '; ' + message + '}'
    f.write(tweet)
    f.close()
tweeting()

如果你想在不同的行中添加'\n'。

尝试以下操作。如果您希望文件中的文本作为字典,只需注意名称和消息中的引号。如果它们不是用户键入的,则必须在将 t 写入文件之前将它们添加到 t:

def tweeting():
    with open('bericht.txt') as f:
        t=f.read()
    if ':' in t:  #that means that t has other elements already
        t=t[:-1]+','
    else:
        t=t[:-1]
    message = input('Put in message:  ')
    name = input('Put in your name: ')
    if name == '':
        name = 'Anonymous'
    t += name + '; ' + message + '}'
    with open('bericht.txt', 'w') as f:
        f.write(t)