small tips.
Here is how to create a temporary text file with python ‘tempfile’ module.
the first one is creating a temporary text file under /tmp directory and the second one is in memory
mint-note untitled # cat virtual_file01.py
__author__ = 'root'
import tempfile
import os
# create a temporary text file under /tmp directory
temp_file = tempfile.NamedTemporaryFile(mode='w+t',suffix='_suffix',prefix='prefix_',dir='/tmp')
try:
temp_file.writelines(['first\n','second\n'])
temp_file.seek(0)
print temp_file
print temp_file.name
for line in temp_file:
print line.rstrip()
finally:
temp_file.close()
# create a virtual text file in memory
temp_memory_file = tempfile.SpooledTemporaryFile(mode='w+t',max_size=10000,prefix='prefix_',suffix='_suffix')
try:
temp_memory_file.writelines(['first\n','second\n'])
temp_memory_file.seek(0)
print temp_memory_file
print temp_memory_file.name
for line in temp_memory_file:
print line.rstrip()
finally:
temp_memory_file.close()
|
mint-note untitled # python virtual_file01.py
<open file '<fdopen>', mode 'w+t' at 0x7f2179c1c4b0>
/tmp/prefix_qONxA9_suffix
first
second
<tempfile.SpooledTemporaryFile instance at 0x7f2179bde878>
None
first
second
|
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.