Error adding items to a file. txt Python3

Asked

Viewed 42 times

0

I’m trying to read a file . txt (currently empty) to check if chat_id already exists, if it already exists, it ends right there. If it doesn’t 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 there is no 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')

1 answer

0

Your code is almost correct, but it’s too.

The method open allows the association of more than one rule for file opening, in case r+, means read and write, so you don’t need to access the file twice.

The rest of its code was practically the same, only 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 method sub, it is necessary to import the module re in the archive:

import re

The ' +','and chat parameters indicate 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
  • Can you explain better the part of re.sub()? It is a module re?

  • ah yes, I will comment on the reply

Browser other questions tagged

You are not signed in. Login or sign up in order to post.