Add new values to txt file

Viewed 258

When a user starts my bot, it gets its user id and stores it in the .txt file.

def verify_id(update, context):
    __location__ = os.path.realpath(os.path.join(os.getcwd(), os.path.dirname(__file__)))
    f = open(os.path.join(__location__, 'users_list_file.txt'), 'w+')
    f_content = f.read().strip().split()
    registered = False
    user_id = str(update.message.from_user.id)
    if user_id in f.read():
          message_ok = "User already existing in DB"
          update.message.reply_text(message_ok)
          registered = True
    else:
        f.write(user_id)
        message_added = "You have been added to my list :)"
        update.message.reply_text(message_added)
    f.close()

Objectives:

  1. If user hasn't ever started the bot, it should add its user id to the .txt file.
  2. If user has already been "registered", the bot should print some text letting the user know that they had already been registred.

Problems:

  1. After it adds a user id to the file, if you retry the same command with the same user it returns the text "You have been added to my list :)", meaning that the file could not be read, to verify if the user id already exists?
  2. I tested with another user, and it seems like the bot erases the value of the last user to replace it with the user id of the latest one. I want just to add, not to replace.

Any suggestion would really help me a lot...

Python version: 3.6.5

2 Answers

with open('file_name.txt','a+') as file: file.write(data)

'a' flag is for appending. 'w' will write to file, but will overwrite its contents. take note to use with when opening files. this way you don't need to worry of closing the file after. take note to add a newline character to each write statement.

file.write('\n' + id)

https://docs.python.org/3/library/functions.html#open

The code provided in the question writes the data every time ('w+') and replaces the old value. Instead of maintaining a plain line by line writing which would always be problematic if you would have to check for later users, I would suggest you maintain a dictionary with list of user_ids and update when there is a change in the list and write it and else just a message is sent.

Below is a simple example in a similar way:

import os
import json
def verify_id(user_id):
    if not os.path.exists("example_users.json"):
        users = {}
        users_list = []
    else:
        f = open("example_users.json")
        users = json.load(f)
        users_list = users["users"]

    if user_id not in users_list:
        users_list.append(user_id)
        users["users"] = users_list
        # Rewrite
        with open("example_users.json", 'w') as f:
            json.dump(users, f)
    else:
        #Some message
        print("Already present")

Below is how the json would look like with some users:

{"users": [1, 132]}

Lets add the same user:

verify_id(1)
Already present

New user:

verify_id(123)
json updated: {"users": [1, 132, 123]}
Related