简体   繁体   English

逐行文本消息传递-python&twilio

[英]Line by line text messaging - python & twilio

I am trying to read each line from a .txt file and text-message it line by line with an enumerated number using Twilio to a phone number (using my own to test). 我正在尝试从.txt文件中读取每一行,并使用Twilio到一个电话号码逐行用枚举的数字对其进行短信(使用我自己的电话进行测试)。

The below reads the file correctly, but only sends a the value of the enumerated list. 以下内容可正确读取文件,但只发送枚举列表的值。

So, I receive: 因此,我收到:

Text Message 1: 1 短信1:1

Text Message 2: 2 短信2:2

Text Message 3: 3 短信3:3

Instead of: 代替:

Text Message 1: 1: Hello! 短信1:1:您好!

Text Message 2: 2: This is working! 短信2:2:这有效!

Text Message 3: 3: Last Line 短信3:最后一行

f = open("file_name")
f = list(enumerate(f, start = 1))
    for line in f:
        text = line
        print text
        client = rest.TwilioRestClient(account_sid, auth_token)
        message = client.messages.create(body=text,
            to="Recipient_Number" 
            from_="Twilio_number")
        message.sid

Twilio developer evangelist here. Twilio开发人员布道者在这里。

When you use enumerate that is creating an iterator of tuples. 当使用enumerate ,将创建一个元组的迭代器。 In your for loop you are only retrieving the first item in each tuple and sending that. for循环中,您仅检索每个元组中的第一项并将其发送。 You can use argument destructuring to get both the index and the text value, like so: 您可以使用参数解构来获取索引和文本值,如下所示:

f = open("file_name")
f = enumerate(f, start = 1)
for index, line in f:
    text = index + ": " + line
    print text
    client = rest.TwilioRestClient(account_sid, auth_token)
    message = client.messages.create(body=text,
        to="Recipient_Number" 
        from_="Twilio_number")
    message.sid

Notably, you also don't need to use list as enumerate returns an iterator that can be used with for ... in . 值得注意的是,您也不需要使用list因为enumerate返回可以与for ... in一起使用的迭代器。

Let me know if this helps at all. 让我知道这是否有帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM