@@ -312,7 +312,7 @@ def _tmp_file_name(
312
312
path : epath .PathLike ,
313
313
subfolder : str | None = None ,
314
314
) -> epath .Path :
315
- """Returns the temporary file name for the given path.
315
+ """Returns the temporary file path dependent on the given path and subfolder .
316
316
317
317
Args:
318
318
path: The path to the file.
@@ -322,9 +322,12 @@ def _tmp_file_name(
322
322
path = epath .Path (path )
323
323
file_name = f'{ _tmp_file_prefix ()} .{ path .name } '
324
324
if subfolder :
325
- return path .parent / subfolder / file_name
325
+ tmp_path = path .parent / subfolder / file_name
326
326
else :
327
- return path .parent / file_name
327
+ tmp_path = path .parent / file_name
328
+ # Create the parent directory if it doesn't exist.
329
+ tmp_path .parent .mkdir (parents = True , exist_ok = True )
330
+ return tmp_path
328
331
329
332
330
333
@contextlib .contextmanager
@@ -334,7 +337,6 @@ def incomplete_file(
334
337
) -> Iterator [epath .Path ]:
335
338
"""Writes to path atomically, by writing to temp file and renaming it."""
336
339
tmp_path = _tmp_file_name (path , subfolder = subfolder )
337
- tmp_path .parent .mkdir (exist_ok = True )
338
340
try :
339
341
yield tmp_path
340
342
tmp_path .replace (path )
@@ -346,20 +348,24 @@ def incomplete_file(
346
348
@contextlib .contextmanager
347
349
def incomplete_files (
348
350
path : epath .Path ,
351
+ subfolder : str | None = None ,
349
352
) -> Iterator [epath .Path ]:
350
353
"""Writes to path atomically, by writing to temp file and renaming it."""
351
- tmp_file_prefix = _tmp_file_prefix ( )
352
- tmp_path = path . parent / f' { tmp_file_prefix } .{ path .name } '
354
+ tmp_path = _tmp_file_name ( path , subfolder = subfolder )
355
+ tmp_file_prefix = tmp_path . name . removesuffix ( f' .{ path .name } ')
353
356
try :
354
357
yield tmp_path
355
358
# Rename all tmp files to their final name.
356
- for tmp_file in path .parent .glob (f'{ tmp_file_prefix } .*' ):
359
+ for tmp_file in tmp_path .parent .glob (f'{ tmp_file_prefix } .*' ):
357
360
file_name = tmp_file .name .removeprefix (tmp_file_prefix + '.' )
358
361
tmp_file .replace (path .parent / file_name )
359
362
finally :
360
363
# Eventually delete the tmp_path if exception was raised
361
- for tmp_file in path .parent .glob (f'{ tmp_file_prefix } .*' ):
362
- tmp_file .unlink (missing_ok = True )
364
+ if subfolder :
365
+ tmp_path .parent .unlink (missing_ok = True )
366
+ else :
367
+ for tmp_file in tmp_path .parent .glob (f'{ tmp_file_prefix } .*' ):
368
+ tmp_file .unlink (missing_ok = True )
363
369
364
370
365
371
def is_incomplete_file (path : epath .Path ) -> bool :
0 commit comments