I am trying to append a message along with a name to an empty dictionary in a text file.
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()
The result I am getting is this:
Tweets = {
}David; Hello everyone
The message goes after the brackets {}. Is there a way to put the message inside the brackets {} ? Thanks for the help.
Try the following. Just take care of the quotes in name and message, if you want the text in your file to be as a dictionary. If they are not typed by user, they must be added to t before t is written in the file:
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)