forked from cool-RR/python_toolbox
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtemp_file_tools.py
More file actions
39 lines (27 loc) · 1.19 KB
/
temp_file_tools.py
File metadata and controls
39 lines (27 loc) · 1.19 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
# Copyright 2009-2014 Ram Rachum.
# This program is distributed under the MIT license.
'''Defines various tools related to temporary files.'''
import tempfile
import shutil
import pathlib
from python_toolbox import context_management
@context_management.ContextManagerType
def create_temp_folder(suffix='', prefix=tempfile.template):
'''
Context manager that creates a temporary folder and deletes it after usage.
After the suite finishes, the temporary folder and all its files and
subfolders will be deleted.
Example:
with create_temp_folder() as temp_folder:
# We have a temporary folder!
assert temp_folder.is_dir()
# We can create files in it:
(temp_folder / 'my_file').open('w')
# The suite is finished, now it's all cleaned:
assert not temp_folder.exists()
Use the `suffix` and `prefix` string arguments to dictate a suffix and/or a
prefix to the temporary folder's name in the filesystem.
'''
temp_folder = pathlib.Path(tempfile.mkdtemp(suffix=suffix, prefix=prefix))
yield temp_folder
shutil.rmtree(str(temp_folder))