A
A
Asriel2021-06-18 21:46:31
Python
Asriel, 2021-06-18 21:46:31

Problems reading and writing the file. How to solve python?

Where is the error in my program? I check the person's id in the telegram for the presence in the file and, if it is not there, I write it down. But for some reason, the bot does not see this id (so far there is only one in the file, and that's mine)

@bot.message_handler(commands=['start'])
def start (message):
  f=open('Файл.txt','a+')
  t = f.readlines() 
  n=t.find(str(message.chat.id))
  if n>-1:
    bot.send_message(message.chat.id, 'привет'+str(n))
  elif n==-1:
    f.write(' '+ str(message.chat.id))
    bot.send_message(message.chat.id, 'привет'+str(n))
  f.close()

Here n (the index of the beginning of the found id) always outputs -1. As a result, the same values ​​are written.

Here I want to count the number of users and it gives me an error, while it works with a regular line
File "new.py", line 23, in test
a=len(re.findall(r'(\d+)' , string))
File "C:\Users\user\AppData\Local\Programs\Python\Python38\lib\re.py", line 24
1, in findall
return _compile(pattern, flags).findall(string)
TypeError: expected string or bytes-like object
@bot.message_handler(commands=['test'])
def test (message):
  f=open('Файл.txt','r')
  string = f.readlines() 
  a=len(re.findall(r'(\d+)', string))
  bot.send_message(message.chat.id,str(a))
  f.close()

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
soremix, 2021-06-18
@Asriel

1. I doubt that the code works. readlines() returns a list, and you are trying to call the string method
2. Try to simply print the contents of the variable t from the first function, you will see that there is essentially no text there, because, when opened in c mode +, the pointer is immediately placed at the end of the file, naturally skipping all other characters
3. Use with ... as
4. Don't do it the way you did. This is a very bad option for data storage. If you need to record user IDs, just use a JSON library and store the IDs as a list of numbers. Write data to a file and read it accordingly through it. As a result, your two big scary functions will be replaced by:

import json


@bot.message_handler(commands=['start'])
def start(message):
    with open('Файл.txt', 'r') as f:
        users = json.load(f)

    if message.chat.id not in users:
        users.append(message.chat.id)
        with open('Файл.txt', 'w') as f:
            json.dump(users, f)

    bot.send_message(message.chat.id, f'Привет, {message.chat.id}')

@bot.message_handler(commands=['test'])
def test (message):
    with open('Файл.txt', 'r') as f:
        users = json.load(f)
    bot.send_message(message.chat.id, f'Количество пользователей: {len(users)}')

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question