繁体   English   中英

如何在无限循环内写入txt文件?

[英]How to write txt files inside a infinite loop?

我试图做一个循环,每次事件发生时在文本文件中写入日期。 但是我无法使其正常工作,因为我需要一个无限循环来运行程序。 如果我将myfile.close()放在循环内,甚至在“ if x [14] ==“ track”:“内,我也会得到:

myfile.write(wri)
ValueError: I/O operation on closed file.

但是,如果我将其放置在循环之外,则文件不会关闭,并且输出文件中不会写入任何内容。

这是代码

while 1 :
    print("yes")
    response = requests.get('https://api.spotify.com/v1/me/player/currently-playing', headers=headers)
    soup2 = BeautifulSoup(response.text, "html.parser")
    x=re.findall('"([^"]*)"', str(soup2)) 

    if isinstance(x, list)==True:
        if len(x)>=15:
            print(x[14])


            if x[14]=="track":


                os.system("TASKKILL /IM spotify.exe")
                sleep(2)
                subprocess.Popen("C:/Users/nebbu/AppData/Roaming/Spotify/Spotify.exe")
                sleep(2)
                import pyautogui
                pyautogui.press("playpause")
                pyautogui.press("l")
                print(x)
                wri=str(date)+"- -"+str(x[13]+": "+str(x[14]))
                myfile.write(wri)


myfile.close()

循环永无止境,我不知道它是否必须结束以关闭文件或是否有另一种方法。

只需创建一个自定义函数,并在每次要将新行添加到文本文件时调用它即可。 例如:

def f(dump):
    file = open('myfile.txt', 'a')
    file.write(dump)
    file.write('\n')
    file.close()

然后将您要即时写入的值传递给它。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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