Error adding items to a Python3 .txt file

0

I'm trying to read a .txt file (currently empty) to check if chat_id already exists, if it already exists, it ends there. If it does not exist ... Add the new chat_id in the last line, but when I run the code and see the file, there is nothing written on it and it does not show any error in the terminal ... Where am I going wrong?

def add_chat(self):
    #print(self.msg_chat_id) output: -10052348214
    with open('bot_chat_ids.txt', 'r') as allchats:
        for chat in allchats:
            if str(self.msg_chat_id) == chat:
                return
    with open('bot_chat_ids.txt', 'a') as allchats:
        allchats.write(str(self.msg_chat_id) + '\n')
    
asked by anonymous 15.10.2018 / 23:42

1 answer

0

Your code is almost correct, but it's too much.

The open method allows joining more than one rule to open the file, in r+ , it means reading and writing, so you do not need to access the file twice.

The rest of your code was pretty much the same, only the functions were grouped with the correct file opening.

#print(self.msg_chat_id) output: -10052348214
with open('bot_chat_ids.txt', 'r+') as allchats:
    for chat in allchats.readlines():
        chat = re.sub(' +','',chat)
        chat = chat.replace('\n', ' ').replace('\r', '')
        if str(self.msg_chat_id) == chat:
            return

    allchats.write(str(self.msg_chat_id) + '\r')

Note: in my example I had to clean the strings to work correctly.

For the operation of the sub method, it is necessary to import the re module into the file:

import re

Parameters '+', '' and chat, indicates to remove all spaces on the right and replace with nothing in the string chat .

Já com o método 'replace' retiramos todas as quebras de linhas.

The txt file was as follows:

-1651654165132
-6513216545
-561652132132
-65163214551
    
16.10.2018 / 01:17