0

I am trying to make a loop that writes in a text file the date each time en event happens. but i can't get it to work since i need an infinite loop to run the program. If i put myfile.close() inside the loop even inside the "if x[14]=="track":" i get:

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

However if i place it outside the loop the file Doesn't close and nothing is written in the output file.

Here is the code

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()

The loop never ends, i don't know if it has to end to close the file or if there is another way of doing it.

Blorgbeard
  • 101,031
  • 48
  • 228
  • 272
  • You can call `flush()` on a file to write out the buffer without closing the file. – Blorgbeard Jun 26 '19 at 23:30
  • 2
    For safely closing the file, you need a `try: ... finally: myfile.close()` block which will close the file no matter what. This can also be accomplished putting your code in a `with open(..., 'w') as myfile: ...` block. But yes, `flush` to write instantly. – FHTMitchell Jun 26 '19 at 23:31
  • Possible duplicate of [Python 2.7 : Write to file instantly](https://stackoverflow.com/questions/18984092/python-2-7-write-to-file-instantly) – Blorgbeard Jun 26 '19 at 23:32
  • Or you could not hold the file open the whole time and just open it in append mode when you want to write to it, then close it again. – Blorgbeard Jun 26 '19 at 23:34

1 Answers1

1

Simply make a custom function and call it for every time you want to add a new line to your text file. For example:

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

and then pass it the values you want to write on the fly.

Seraph Wedd
  • 864
  • 6
  • 14
  • Using `with` would be less error prone, e.g. `with open(‘myfile.txt’, ‘a’) as file: file.write(dump); file.write(‘\n’)` This is probably small enough to not need a separate function - but this is a matter of choice. – AChampion Jun 26 '19 at 23:50