Skip to content

Instantly share code, notes, and snippets.

@dstufft
Created February 24, 2014 19:40
Show Gist options
  • Select an option

  • Save dstufft/9195493 to your computer and use it in GitHub Desktop.

Select an option

Save dstufft/9195493 to your computer and use it in GitHub Desktop.
# Option 1
filename = None
try:
fileobj = tempfile.NamedTemporaryFile(delete=False)
filename = fileobj.name
fileobj.close() # Required because not all platforms can reopen a file a second time
with open(filename, "w") as fp:
fp.write(pkgutil.get_data("something.txt"))
actually_call_a_thing(filename)
finally:
if filename is not None:
os.remove(filename)
# Option 2
with pkgutil.get_data_file("something.txt") as fileobj:
actually_call_a_thing(fileobj.name)
@brettcannon

Copy link
Copy Markdown

What's wrong with the following (I'm sure there's something I just don't know exactly what)?

with tempfile.NamedTemporaryFile('wb') as file:
  file.write(pkgutil.get_data("something.txt")
  file.flush()
  actually_call_a_thing(file.name)

@dstufft

dstufft commented Feb 24, 2014

Copy link
Copy Markdown
Author

From the docs of tempfile.NamedTemporaryFile

Whether the name can be used to open the file a second time, while the named temporary file is still open, varies across platforms (it can be so used on Unix; it cannot on Windows NT or later)

@dstufft

dstufft commented Feb 24, 2014

Copy link
Copy Markdown
Author

The above means that you have to close the file for it to work on Windows, which means you have to set delete=False. Also because there are GCs other than ref count you have to explicitly close it and not just wait for it to go out of scope, so you have to do the 3 line dance at the top instead of just filename = tempfile.NamedTemporaryFile(delete=False).name. Although I realized it could be simplified somewhat by doing:

filename = None
try:
    with tempfile.NamedTemporaryFile(delete=False) as fileobj:
        filename = fileobj.name
        fileobj.write(pkgutil.get_data("something.txt"))

    actually_call_a_thing(filename)
finally:
    if filename is not None:
        os.remove(filename)

So that's not quite as annoying to do as my original snippet, but it's still not as nice as the second.

@cournape

Copy link
Copy Markdown

@dstufft what I do in those cases (we support windows pervasively at work), is something like

with tempfile.NamedTemporaryFile(delete=False) as fileobj:
    filename = fileobj.name

although I prefer putting this in a separate function to make the intent (side effect) clearer

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment