I want to create a file, display it in a web browser, then delete the file as soon as it is loaded in the browser.
This is my attempt (I use this for SVG files, but I made it use a txt file for a simple example). For me, the file is deleted before it can be loaded unless I insert a pause.
import webbrowser
import os
def open_in_browser(file_location):
"""Attempt to open file located at file_location in the default web
browser."""
new = 2 # open in a new tab, if possible
webbrowser.get().open(file_location, new=new)
tmpfilename1 = os.path.join(os.getcwd(), "test1.txt")
tmpfilename2 = os.path.join(os.getcwd(), "test2.txt")
with open(tmpfilename1, 'w') as f:
f.write("Hello World!")
open_in_browser(tmpfilename2)
os.remove(tmpfilename1)
# If I pause before deleting, everything works fine.
import time
with open(tmpfilename2, 'w') as f:
f.write("Hello again!")
open_in_browser(tmpfilename2)
time.sleep(1) # Pause.
os.remove(tmpfilename2)
Anyone know a simple fix for this that doesn't require a pause? Thanks for reading.