import tempfile
# Creates a file and returns a tuple containing both the handle and the path.
handle, path = tempfile.mkstemp()
with open(handle, "w") as f:
f.write("Hello, World!");
import tempfile
with tempfile.TemporaryFile() as fp:
name = fp.name
fp.write("Hello World!") # Write a string using fp.write()
content = fp.read() # Read the contents using fp.read()
print(f"Content of file {name}: {content}")
print("File is now deleted")
import tempfile
import os
# Creates a file and returns a tuple containing both the handle and the path.
handle, path = tempfile.mkstemp()
# full path of temp file
print("Temp file path:", path)
# output example /var/folders/mk/2ghcw18s6xx2fxjv_ybk7x640000gn/T/tmp465djfe4
# write to temp file
with open(handle, "w") as f:
f.write("Hello, World!")
# read from temp file
with open(path, "r") as f:
print(f.readlines())
# output ['Hello, World!']
# delete the temporary file
os.unlink(path)