header 在写入 csv 文件时每隔一行重复一次

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

使用 Tweepy,我正在使用 python 写入 csv 文件并且 header 每隔一行重复一次

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])

您的脚本应更改为:

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])

您只需要创建一次 thewriter object,当然,您只想创建一次 headers,而不是像您看到的那样每隔一行创建一次。将内容移出循环遍历行的 for 循环可以实现这一点。