Skip to content

Instantly share code, notes, and snippets.

@kshirsagarsiddharth
Created August 6, 2020 05:33
Show Gist options
  • Select an option

  • Save kshirsagarsiddharth/0294c4c95bd223dad895b2034ad97f22 to your computer and use it in GitHub Desktop.

Select an option

Save kshirsagarsiddharth/0294c4c95bd223dad895b2034ad97f22 to your computer and use it in GitHub Desktop.
creating temp files
# creating temp file using common pattern for making up names
import os
import tempfile
print('Building a filename with PID:')
filename = 'custon_temp_file.{}.txt'.format(os.getpid())
with open(filename, 'w+b') as temp:
print('temp:')
print(' {!r}'.format(temp))
print('temp.name:')
print(' {!r}'.format(temp.name))
os.remove(filename)
"""
Output:
Building a filename with PID:
temp:
<_io.BufferedRandom name='custon_temp_file.6216.txt'>
temp.name:
'custon_temp_file.6216.txt'
"""
# creating temp file using tempfile module
import tempfile
with tempfile.TemporaryFile() as temp:
print(temp)
print(temp.name)
'''
<tempfile._TemporaryFileWrapper object at 0x000001E562106F48>
C:\Users\sidha\AppData\Local\Temp\tmp00dwsbdt
'''
# reading and writing from a temp file
# default mode of writing for a temp file is "w+b"
import tempfile
with tempfile.TemporaryFile() as temp:
temp.write(b"This is a temp file")
temp.seek(0)
print(temp.read())
'''
b'This is a temp file'
'''
# opening the file in text mode
import tempfile
with tempfile.TemporaryFile(mode = "w+t") as temp:
temp.writelines(['Line1\n','Line2\n'])
temp.seek(0)
print(temp.read())
'''
Line1
Line2
'''
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment