1

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.

mathandy
  • 1,892
  • 25
  • 32
  • Note: python has a facility for temporary files see https://docs.python.org/2/library/tempfile.html, not that this will explicitly fix your issue. If you are concerned about the contents of the file then you could explore `os.mkfifo()` which would only allow the data to be read once. – AChampion Oct 07 '15 at 05:02
  • @AChampion, this sounds like it might be what I need, but os.mkfifo() is available on Unix only. I need a solution that works on Windows also. Actually I'm unable to test this even as my windows laptop has a hardware issue currently that prevents me from running VMs. – mathandy Oct 09 '15 at 21:35

0 Answers0