簡體   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