The code below works but does not loop through each name in the txt file (loops only when i just want to print their names from the text file) , it only returns the details of the last user in the list rather than returning individual user details one by one. i use Phyton twitter wrapper

Txt file have about 50 users. And always returns details of the last user in the list.

Thank you for your time.

import csv, math, time
import twitter as twitterapi

api = twitter.Api(consumer_key='uTZrt1d5y3ZStmHqIIgsg', 
consumer_secret='sqZg5AhJoBosLrnM', 
access_token_key='221834337-VjCsNhcoA1', 
access_token_secret='cO0oyhP'uTZrt1d5y3ZStmHqIIgsg')

listofnames = file('twit.txt').readlines()
listofnames = [name.strip() for name in listofnames]

csvfile=open('twittercounts.csv','ab')
csvout=csv.writer(csvfile,dialect='exc…

for name in listofnames:
account = api.GetUser(name)
followers = account.followers_count
csvout.writerow([name, followers])
print name + ", " + str(followers)

csvfile.close()

You should use open instead of file at line for list_of_names:

listofnames = file('twit.txt').readlines()
listofnames = [name.strip() for name in listofnames]
#-->
list_of_names=[name.strip() for name in open('twit.txt')]

But actually in code you only use it once, so making the list is kind of wasteful, generator would suffice:

for name in (name.strip() for name in open('twit.txt')):
    print name

Your indention is not OK in post, use code-tags.

This implies

it only returns the details of the last user in the list

This implies that you only write the last name. You code should be indented as follows, with the write statement under the for() loop.

for name in listofnames:
    account = api.GetUser(name)
    followers = account.followers_count
    csvout.writerow([name, followers])
    print name + ", " + str(followers)

csvfile.close()
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.