Search code examples
python-3.xtweepy

The header repeats every other row when writing to a csv file


Using Tweepy, I am writing to a csv file with python and the header repeats every other row

x=0
x+=1

with open('NAME' + str(x) + '.csv', 'w' , newline='') as f:
    for user in tweepy.Cursor(api.followers, screen_name="Name").items(5):
        thewriter = csv.writer(f)
        thewriter.writerow(['Username', 'location'])
        thewriter = csv.writer(f)
        thewriter.writerow([user.screen_name , user.location])

Solution

  • Your script should change to this:

    x=0
    x+=1
    
    with open('NAME' + str(x) + '.csv', 'w' , newline='') as f:
            thewriter = csv.writer(f)
            thewriter.writerow(['Username', 'location'])
        for user in tweepy.Cursor(api.followers, screen_name="Name").items(5):
            thewriter.writerow([user.screen_name , user.location])
    

    You only need to create thewriter object one time, and of course, you only want to create the headers once, not every other row as you saw. Moving things out of the for loop where you are looping through the rows enables that.