Search code examples
pythonbotstweepy

how to read lines in sequence continuously in python


I am trying to make a tweet bot using tweepy, that tweets continuously using lines from a text file

s = api.get_status(statusid) 
m = random.choice(open('tweets.txt').readlines()).strip("\n")
api.update_status(status=m, in_reply_to_status_id = s.id)
print("[+] tweeted +1")

The file contains:

1st line
2nd line
3rd line
...
100th line

Instead of choosing only one random line, I want to make it tweet continuously from 1st line, 2nd line, ... and so on, after all the lines has tweeted.

And also I want to make it every time it tweets, the number increases like

[+] tweeted +1
[+] tweeted +2
...
[+] tweeted +100

Solution

  • This seems like a pretty straightforward situation to use a loop in. Files in Python are iterable, so you can just do:

    with open('tweets.txt') as file: # a with statement ensures the file will get closed properly
        for line in file:
            ... # do your stuff here for each line
    

    Since you want to have a running count of the number of lines you've used, you may want to add a call to enumerate, which will pair each value you iterate over with a number (starting at zero by default, but you can tell it to start at 1 instead):

    with open('tweets.txt') as file:
        for num, line in enumerate(file, start=1):
            ...