读取和写入文件的速度不够快,我的脚本无法识别更改

Can't read and write files fast enough for my script to recognize changes

我正在编写一个脚本,当我最喜欢的 YouTuber Casey Neistat 上传新视频时,该脚本最终能够通过 Twitter 帐户发送推文。然而,为了做到这一点,我写了一个程序,当它识别出以前的YouTube link 的列表不包括最近上传的视频。我制作了两种方法,一种称为 'mainloop',它一遍又一遍地运行,以查看之前所有 Casey Neistat 的视频列表是否与从方法 [=17= 中检索到的一串新的 link 相同].然而,我遇到的问题是,一旦程序识别出新视频,它就会转到方法 'getNewURL',该方法将采用 'output.txt' 文件中记录的第一个 link。但是当我说打印这个新的 URL 时,它说那里什么也没有。我的直觉是,这是因为 python 读写 output.txt 文件的速度不够快,但我可能错了。

我的代码如下:

import bs4
import requests
import re
import time
import tweepy


'''
This is the information required for 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') for a 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 at this time")

    else:
        print("There is a new video!")

        print('...')
        print('Writing to new text file')
        print('...')


        f = open("output.txt", "w")
        f.write(results)

        print('...')
        print('Done writing to 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

您从不关闭文件,这可能就是问题所在。例如,在 mainLoop() 你应该有:

f = open("output.txt", "w")
f.write(results)
f.close()

甚至更好:

with open('output.txt', 'w') as output:
    output.write(results)

一般来说,最好在所有打开文件的地方使用 with 语句(即使它处于 'r' 模式),因为它会自动关闭文件文件,它还清楚地表明代码的哪一部分在给定时间 on/with 文件。