简体   繁体   中英

Tweepy - Text file not being written to

I'm trying to extract tweets using the historical Twitter API from Twitter and then copying them onto a text file. However, the text file is not being written to at all.

I've tried writing to a CSV though that has not worked either. It is being run on Python 3.6 and all the libraries are installed. I am not getting any error messages suggesting a problem with the text file.

import tweepy
import sys
import os
import codecs

CONSUMER_KEY = "" # These are removed for obvious reasons!
CONSUMER_SECRET = ""
ACCESS_TOKEN = ""
ACCESS_TOKEN_SECRET = ""

auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
auth.set_access_token(ACCESS_TOKEN, ACCESS_TOKEN_SECRET)

api = tweepy.API(auth)

f = codecs.open('C:\\Users\\ctrh1\\Desktop\\tweets30apr.txt', "w", encoding="utf-8")

for tweet in tweepy.Cursor(api.search,
                       q="brexit",
                       count=100,
                       since="2019-04-28",
                       until="2019-04-29",
                       lang="en").items():
    print(tweet.text)
    f.write(tweet.text)

I would expect to have the text from some tweets written to file f, but it is blank after I have stopped the code from running.

Maybe you can first try if you are authorized to write with this minimal example:

file_name = 'C:\\Users\\ctrh1\\Desktop\\tweets30apr.txt'

with open(file_name, 'w') as f:
    f.write("Hello World!")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM