skip to Main Content

I am creating a short script which tweets automatically via twitter API. Besides setting up the API credentials (out of the scope for the question) I import the following library:

import os

I have set my working directory to be a folder where I have 3 photos. If I run os.listdir('.') I get the following list.

['Image_1.PNG',
 'Image_2.PNG',
 'Image_3.jpg',]

“mylist” is a list of strings, practically 3 tweets.

The code that posts in Twitter automatically looks like that:


for image in os.listdir('.'):
    for num in range(len(mylist)):
        api.update_with_media(image, mylist[num])

The code basically assigns to the first image a tweet and posts. Then to the same image the second tweet and posts. Again first image – third tweet. Then it continues the cycle to second and third image altogether 3*3 9 times/posts.

However what I want to achieve is to take the first image with the first tweet and post. Then take second image with second tweet and post. Third image – third tweet. Then I want to run the cycle one more time: 1st image – 1st tweet, 2nd image – 2nd tweet …etc.

2

Answers


  1. Use zip to iterate through two (or more) collections in parallel

    for tweet, image in zip(mylist, os.listdir('.')):
        api.update_with_media(image, tweet)
    

    To repeat it more times, you can put this cycle inside another for

    Login or Signup to reply.
  2. Assuming the length of os.listdir(‘.’) and mylist are equal:

    length = len(mylist) # If len(os.listdir('.')) is greater than len(mylist),
    # replace mylist with os.listdir('.')
    
    imageList = os.listdir('.')
    iterations = 2 # The number of time you want this to run
    for i in range(0,iterations):
        for x in range(0, length):
            api.update_with_media(imageList[x], mylist[num])
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search