Function to create and return a unique temporary file with the given extension, if provided. Parameters ---------- extension : str The extension of the temporary file to be created dir : str If ``dir`` is not None, the file will be created in that directory; oth
(extension="", dir=None)
| 331 | |
| 332 | @contextmanager |
| 333 | def tmpfile(extension="", dir=None): |
| 334 | """ |
| 335 | Function to create and return a unique temporary file with the given extension, if provided. |
| 336 | |
| 337 | Parameters |
| 338 | ---------- |
| 339 | extension : str |
| 340 | The extension of the temporary file to be created |
| 341 | dir : str |
| 342 | If ``dir`` is not None, the file will be created in that directory; otherwise, |
| 343 | Python's default temporary directory is used. |
| 344 | |
| 345 | Returns |
| 346 | ------- |
| 347 | out : str |
| 348 | Path to the temporary file |
| 349 | |
| 350 | See Also |
| 351 | -------- |
| 352 | NamedTemporaryFile : Built-in alternative for creating temporary files |
| 353 | tmp_path : pytest fixture for creating a temporary directory unique to the test invocation |
| 354 | |
| 355 | Notes |
| 356 | ----- |
| 357 | This context manager is particularly useful on Windows for opening temporary files multiple times. |
| 358 | """ |
| 359 | extension = extension.lstrip(".") |
| 360 | if extension: |
| 361 | extension = "." + extension |
| 362 | handle, filename = tempfile.mkstemp(extension, dir=dir) |
| 363 | os.close(handle) |
| 364 | os.remove(filename) |
| 365 | |
| 366 | try: |
| 367 | yield filename |
| 368 | finally: |
| 369 | if os.path.exists(filename): |
| 370 | with suppress(OSError): # sometimes we can't remove a generated temp file |
| 371 | if os.path.isdir(filename): |
| 372 | shutil.rmtree(filename) |
| 373 | else: |
| 374 | os.remove(filename) |
| 375 | |
| 376 | |
| 377 | @contextmanager |