【问题标题】:Appending to dictionary in text file in Python inside the brackers {}在括号 {} 内附加到 Python 文本文件中的字典
【发布时间】:2021-01-26 17:31:31
【问题描述】:

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

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

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

【问题讨论】:

    标签: python file dictionary append brackets


    【解决方案1】:

    试试下面的。如果您希望文件中的文本作为字典,请注意名称和消息中的引号。如果它们不是用户输入的,则必须在将 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)
    

    【讨论】:

    • 是的,这解决了。请问,当你说 ' t = t[:-1] + ',' 时会发生什么?为什么是 [:-1] ?
    • 这是用逗号分隔字典中的项目。但是它必须检查是否没有其他元素,在这种情况下它不应该添加逗号。我将在代码中为此添加一个条件
    • 添加了一些条件。如果':'已经在文本中,这意味着已经有另一个元素,那么将添加逗号,否则不会
    • ps:不要忘记为已接受的答案和/或其他答案投票 :) 干杯!
    • 它以前工作过,因为字典中已经有元素。但这更好。
    【解决方案2】:

    您没有输入任何这样的括号。只需按如下方式添加括号 -

    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'。

    【讨论】:

    • 遗憾的是,这还不能解决我的问题。我希望消息进入文本文件中的字典内部,而不是字典后面。
    • 您能分享一个您正在寻找的示例输出吗?
    猜你喜欢
    • 2019-05-01
    • 2015-10-22
    • 2019-03-14
    • 2023-03-10
    • 2021-08-28
    • 1970-01-01
    • 2013-08-09
    • 2018-01-11
    • 1970-01-01
    相关资源
    最近更新 更多