python - Can't read and write files fast enough for my script to recognize changes -
im writing script able tweet form twitter account when favourite youtuber casey neistat uploads new video. however, in order that, wrote program (should) able compare 'output.txt' file of links previous videos new 1 when recognizes previous list of youtube links not include uploaded video. made 2 methods, 1 called 'mainloop' runs on , on see if previous list of casey neistat's videos same string of new links retrieved method 'getneistatnewvideo'. problem i'm having, once program recognizes new video, goes method 'getnewurl' take first link recorded in 'output.txt' file. when print new url, says there nothing there. hunch because python not reading , writing output.txt file fast enough, may wrong.
my code follows:
import bs4 import requests import re import time import tweepy ''' information required tweepy consumer_key = consumer_secret = access_key = access_secret = auth = tweepy.oauthhandler(consumer_key, consumer_secret) auth.set_access_token(access_key, access_secret) api = tweepy.api(auth) end of tweepy information ''' root_url = 'https://www.youtube.com/' index_url = root_url + 'user/caseyneistat/videos' def getneistatnewvideo(): response = requests.get(index_url) soup = bs4.beautifulsoup(response.text) return [a.attrs.get('href') in soup.select('div.yt-lockup-thumbnail a[href^=/watch]')] def mainloop(): results = str("\n".join(getneistatnewvideo())) past_results = open('output.txt').read() if results == past_results: print("no new videos @ time") else: print("there new video!") print('...') print('writing new text file') print('...') f = open("output.txt", "w") f.write(results) print('...') print('done writing new text file') print('...') getnewurl() def getnewurl(): url_search = open('output.txt').read() url_select = re.search('(.+)', url_search) print("new url found: " + str(url_select)) while true: mainloop() time.sleep(10) pass
you never close files , may problem. instance, in mainloop()
should have:
f = open("output.txt", "w") f.write(results) f.close()
or better:
with open('output.txt', 'w') output: output.write(results)
in general, it's idea use with
statement in places open file (even if it's in 'r' mode) automatically take care of closing file , makes clear section of code working on/with file @ given time.
Comments
Post a Comment