Context managers for managing temporary files and directories.
Project description
Context managers for managing temporary files and directories.
with temp_dir(suffix='', prefix='tmp', parent_dir=None, make_cwd=False):
...
@in_temp_dir()
...
with temp_file(
content=None,
suffix='',
prefix='tmp',
parent_dir=None,
binary=True):
...
Installation:
$ pip install temporary
Temporary Directory Examples
>>> from temporary import temp_dir, in_temp_dir
The temporary directory is created when entering the context manager, and deleted when exiting it:
>>> from os.path import exists, isdir
>>> with temp_dir() as d:
... assert isdir(d)
>>> assert not exists(d)
This time let’s make the temporary directory our working directory:
>>> from os import getcwd
>>> with temp_dir(make_cwd=True) as d:
... assert d == getcwd()
>>> assert d != getcwd()
The suffix, prefix, and parent_dir options are passed to the standard tempfile.mkdtemp() function:
>>> from os.path import basename, dirname
>>> with temp_dir() as p:
... with temp_dir(suffix='suf', prefix='pre', parent_dir=p) as d:
... assert dirname(d) == p
... assert basename(d).startswith('pre')
... assert basename(d).endswith('suf')
This function can also be used as a decorator, with the in_temp_dir alias:
>>> @in_temp_dir()
... def my_function():
... assert old_cwd != getcwd()
...
>>> old_cwd = getcwd()
>>> my_function()
>>> assert old_cwd == getcwd()
Temporary Files Examples
>>> from temporary import temp_file
The temporary file is created when entering the context manager and deleted when exiting it.
>>> from os.path import exists, isfile
>>> with temp_file() as f_name:
... assert isfile(f_name)
>>> assert not exists(f_name)
The user may also supply some content for the file to be populated with:
>>> with temp_file('hello!') as f_name:
... with open(f_name) as f:
... assert f.read() == 'hello!'
The temporary file can be placed in a custom directory:
>>> from os.path import dirname
>>> from temporary import temp_dir
>>> with temp_dir() as d_name:
... with temp_file(parent_dir=d_name) as f_name:
... assert dirname(f_name) == d_name
If, for some reason, the user wants to delete the temporary file before exiting the context, that’s okay too:
>>> import os
>>> with temp_file() as f_name:
... os.remove(f_name)
Project details
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Hashes for temporary-1.0.0-py2.py3-none-any.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | f60a8c82b2e2279e134b7853b657c745a0f29b875b4c7147497bb76b739ba389 |
|
MD5 | 67d2254a13908545770adc4dccb24a60 |
|
BLAKE2b-256 | 99aa5b38d184baf2da27078bb488a85d2c2ce368ff145f654f780c1434684ba0 |