Showing posts with label temporary file. Show all posts
Showing posts with label temporary file. Show all posts

Monday, August 11, 2014

Cross-platform way of working with python temporary file and directory

import tempfile
import os

print 'Temp Directory:', tempfile.gettempdir()
f = tempfile.NamedTemporaryFile(delete=False, prefix='_PREFIX_', suffix='_SUFFIX_')
print 'File Name:', f.name;
f.write('Something On Temporary File... 1')
f.write('\nSomething On Temporary File... 2')
f.seek(0)
print '\nFile Contents: '
print f.read()
print '\nFile Contents Line By Line: '
f.seek(0)
for line in f:
    print '--->', line.rstrip()
f.close()
print '\nFile Exists:', os.path.exists(f.name)
os.unlink(f.name)
print '\nFile Exists:', os.path.exists(f.name)
dirc = tempfile.mkdtemp()
print '\nDirectory Name:', dirc
print '\nDirectory Exists:', os.path.exists(dirc)

for num in range(1, 3):
    fname = os.path.join(dirc, str(num) + '.file');
    print '\nCustom File:', fname
    tpfile = open(fname, 'w+b');
    tpfile.write('Writting Something...' + str(num));
    tpfile.seek(0);
    print 'File Contents:'
    print tpfile.read();
    tpfile.close()
    print 'File Exists:', os.path.exists(tpfile.name)
    os.unlink(tpfile.name)
    print 'File Exists:', os.path.exists(tpfile.name)

print '\nDirectory Name:', dirc
print '\nDirectory Exists:', os.path.exists(dirc)
os.removedirs(dirc)
print '\nDirectory Exists:', os.path.exists(dirc)

Output would be like this:

Temp Directory: c:\users\user\appdata\local\temp
File Name: c:\users\user\appdata\local\temp\_PREFIX_mrr8st_SUFFIX_

File Contents: 
Something On Temporary File... 1
Something On Temporary File... 2

File Contents Line By Line: 
---> Something On Temporary File... 1
---> Something On Temporary File... 2

File Exists: True

File Exists: False

Directory Name: c:\users\user\appdata\local\temp\tmpdvd8ej

Directory Exists: True

Custom File: c:\users\user\appdata\local\temp\tmpdvd8ej\1.file
File Contents:
Writting Something...1
File Exists: True
File Exists: False

Custom File: c:\users\user\appdata\local\temp\tmpdvd8ej\2.file
File Contents:
Writting Something...2
File Exists: True
File Exists: False

Directory Name: c:\users\user\appdata\local\temp\tmpdvd8ej

Directory Exists: True

Directory Exists: False