Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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