L
L
Lavrenty Fedotov2017-02-17 19:07:58
Python
Lavrenty Fedotov, 2017-02-17 19:07:58

How to avoid duplicates when writing chat.id to a file?

There is a code:

global sub
sub = [line.rstrip('_\n') for line in open(subfile,'rt')]
if str(m.chat.id) not in sub:
  with open(subfile, 'a') as f:
    f.write(str(m.chat.id) + " \n")
else:
        bot.send_message(m.chat.id, 'hi')

It writes m.chat.id to the sub file. In theory, it should only do it once, but it does it every time, regardless of if else, and because of this, duplicates appear. How to fix it?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Ilyas, 2017-02-17
@id2669099

this is exactly how it should work

f = open('file.txt', 'r')
for line in f:
    if str(m.chat.id) in line:
        f.close()
        break
    else:
        f = open('file.txt', 'a')
        f.write(str(m.chat.id) + '\n')
        f.close()
        bot.send_message(m.chat.id, 'hi')

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question