June 2018
Beginner
508 pages
13h 8m
English
Sometimes, it's very useful to be able to create a temporary directory or file when running some code. For example, when writing tests that affect the disk, you can use temporary files and directories to run your logic and assert that it's correct, and to be sure that at the end of the test run, the test folder has no leftovers. Let's see how you do it in Python:
# files/tmp.pyimport osfrom tempfile import NamedTemporaryFile, TemporaryDirectorywith TemporaryDirectory(dir='.') as td: print('Temp directory:', td) with NamedTemporaryFile(dir=td) as t: name = t.name print(os.path.abspath(name))
The preceding example is quite straightforward: we create a temporary directory in the current one ("."), and we create ...
Read now
Unlock full access