forked from cirosantilli/python-cheat
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtempfile_cheat.py
More file actions
executable file
·54 lines (41 loc) · 1.11 KB
/
tempfile_cheat.py
File metadata and controls
executable file
·54 lines (41 loc) · 1.11 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
#!/usr/bin/env python
"""
## tempfile
Create temporary files and directories.
<http://www.doughellmann.com/PyMOTW/tempfile/
"""
import shutil
import tempfile
# The filename is given by dir + prefix + random + suffix.
#
# - dir defaults to gettempdir()
# - prefix defaults to gettempprefix()
#
# Does not return a string, but an object.
# Use `.name` to get the path string.
temp = tempfile.NamedTemporaryFile(
#dir = '/tmp',
prefix = 'prefix_',
suffix = '_suffix',
)
try:
print('temp = ' + str(temp))
print('temp.name = ' + temp.name)
temp.write('asdf')
temp.flush()
finally:
# File is deleted on close!
temp.close()
# Make a temporary directory instead of file.
# Returns a path string.
directory_name = tempfile.mkdtemp(
dir = '/tmp',
prefix = 'prefix_',
suffix = '_suffix',
)
print('mkdtemp = ' + directory_name)
shutil.rmtree(directory_name)
# The default directory that will hold all of the temporary files:
print('gettempdir() = ' + tempfile.gettempdir())
# The basename prefix for new file and directory names:
print('gettempprefix() = ' + tempfile.gettempprefix())