Skip to content

Instantly share code, notes, and snippets.

@ychennay
Created August 8, 2021 17:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ychennay/319e14f35becb93b556e6637c7f5ce8b to your computer and use it in GitHub Desktop.
Save ychennay/319e14f35becb93b556e6637c7f5ce8b to your computer and use it in GitHub Desktop.
temporary file implicit close example
from tempfile import NamedTemporaryFile
import os
def test():
tf = NamedTemporaryFile()
yield tf.name
if __name__ == "__main__":
temp_file_generator = test()
temp_file_name = next(temp_file_generator)
print(f"Temp file was saved at,", temp_file_name)
# this is before we exit from the function
print(os.path.exists(temp_file_name)) # True
try:
next(temp_file_generator)
except StopIteration:
pass
# this is after we exit from the function
print(os.path.exists(temp_file_name)) # False
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment