Skip to content

Instantly share code, notes, and snippets.

@elowy01
Last active July 7, 2022 13:51
Show Gist options
  • Save elowy01/80490ea42ffe3403655a723d34fc40dc to your computer and use it in GitHub Desktop.
Save elowy01/80490ea42ffe3403655a723d34fc40dc to your computer and use it in GitHub Desktop.
import os
import tempfile
temp = tempfile.NamedTemporaryFile()
try:
print 'temp:', temp
print 'temp.name:', temp.name
finally:
# Automatically cleans up the file
temp.close()
print 'Exists after close:', os.path.exists(temp.name)
###### Writing to a named temp file #########
# Import tempfile module
import tempfile
# Import os module
import os
# Declare object to open temporary file for writing
tmp = tempfile.NamedTemporaryFile('w+t')
# Declare the name of the temporary file
tmp.name="temp.txt"
try:
# Print message before writing
print('Write data to temporary file...')
# Write data to the temporary file
tmp.write('This is a temporary content.')
# Move to the starting of the file
tmp.seek(0)
# Read content of the temporary file
print('Read the content of temporary file: \n{0}'.format(tmp.read()))
finally:
# Remove the file automatically
tmp.close()
# Check the file exist or not
if(os.path.exists(tmp.name)):
print('The file exist')
else:
print('The file does not exist')
# Working on text mode and dealing with a temp file without name
# We will write something to the file and read it back
import tempfile
f = tempfile.TemporaryFile(mode='w+t')
try:
f.writelines(['first\n', 'second\n'])
f.seek(0)
for line in f:
print line.rstrip()
finally:
f.close()
"""
$ python tempfile_TemporaryFile_text.py
first
second
"""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment