P
P
pivazik2020-06-01 20:50:39
Python
pivazik, 2020-06-01 20:50:39

Python JSON how to wrap a line in a file?

Hello, a question related to saving data in JSON, when the user enters data, the line starts to fill in and at the end some data simply disappears, I tried to transfer the line using the "\n" method as in Python itself, but it did not work and the line with "\n" deleted after updating the dictionary.
This is how the dictionary itself looks like, which is written to the "nicks.json" folder:
5ed53f024ce5f276107286.png
When this dictionary reaches the end of the line, a problem arises in which the data from any line disappears and so on in a circle.
Here is a script that writes information to the "nicks.json" folder:

if msg.startswith('%ник'):
    nick = msg.lstrip('%ник').strip()
    user_id = event.obj["from_id"]
    if len(nick) < 3:
      vk.method("messages.send", {"peer_id": event.object.peer_id, "message": "⚠ | Никнейм слишком короткий", "random_id": 0})
    else:
      vk.method("messages.send", {"peer_id": event.object.peer_id, "message": "✔ | Теперь @id" + str(user_id) + "(ваш) никнейм: " + str(nick) + ".", "random_id": 0})
      users_nick[user_id] = nick
      with open('nicks.json', 'w') as f:
        f.write(json.dumps(users_nick))

users_nick = {} #обычный словарь из которого идёт запись в файл.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Karbivnichy, 2020-06-01
@pivazik

So: the data is overwritten each time the file is accessed. And so: added to the end of the file.
with open('nicks.json', 'w') as f:
with open('nicks.json', 'a') as f:

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question