Read . txt file and write each line in a variable - Python

Asked

Viewed 1,673 times

-1

Good afternoon, you guys! I’m having trouble recording each line into a variable to be used in a for. In my file . txt has a list of several contacts, e.g.: [email protected], [email protected].

What I need to do is use this file . txt to send contact messages by contact. Here’s an example of how I tried to make the code:

contatos = open("contatos.txt", "r")
linhas = contatos.readlines()
for linha in linhas:
    msg = "Boa tarde"
    mac.send_message_to(msg, linha)
contatos.close()

This mac.send_message_to() method is being imported from another file... Who can help me I thank!

  • 1

    And what’s the problem?

1 answer

1

From what I understand, you just want to save the contacts so they can be accessed one by one. If the file is a contact per line, just insert it into an array (list) and access it later. If the file is several per line, separated by some character (comma, colon, etc.), you will need to process the line before inserting it into the list. Below is an example that should work.

contatos = open("contatos.txt", "r")
contatos_array = []
linhas = contatos.readlines()
for linha in linhas:
    contatos_array.append(linha)
contatos.close()

for contato in contatos_array:
    msg = "Boa tarde"
    mac.send_message_to(msg, contato)
  • Thanks Lucas Amparo, that’s exactly what I was looking for... But I have an error in the execution of this method -> mac.send_message_to. Returned: Typeerror: () takes 0 positional Arguments but 2 Were Given ...

  • This reported error says that the function "send_message_to" has no argument (0 positional Arguments) and vc is trying to pass 2 (but 2 Were Given). See the method documentation to see the correct way to send the data. You probably have to set the content and the recipient, type setMsg() and setReceiver(), and then send the message with send_mesage...

  • According to the author’s own documentation -> https://github.com/danielcardeenas/whatsapp-framework/ code
mac.send_message_to("Hello", "5218114140740")
"""
def send_message_to(str_message, phone_number, disconnect_after=True):
 jid = Jid.normalize(phone_number)
 send_message(str_message, jid)
code This is the way to send a message, and from what I understand I am following what is requested, just trying to use + 1 contact per message...

Browser other questions tagged

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