Skip to content

Commit cce6748

Browse files
committed
Fix atomic file operations support on Windows. #121
1 parent a35062c commit cce6748

1 file changed

Lines changed: 7 additions & 7 deletions

File tree

src/fsutil/io.py

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@
22

33
import json
44
import os
5-
import platform
65
import tempfile
76
from collections.abc import Generator
87
from datetime import datetime
@@ -137,23 +136,24 @@ def _write_file_atomic(
137136
if append:
138137
content = read_file(path, encoding=encoding) + content
139138
dirpath, _ = split_filepath(path)
140-
auto_delete_temp_file = False if platform.system() == "Windows" else True
139+
temp_path = None
141140
try:
142141
with tempfile.NamedTemporaryFile(
143142
mode=mode,
144143
dir=dirpath,
145-
delete=auto_delete_temp_file,
144+
delete=False,
146145
# delete_on_close=False, # supported since Python >= 3.12
147146
encoding=encoding,
148147
) as file:
149148
file.write(content)
150149
file.flush()
151150
os.fsync(file.fileno())
152151
temp_path = file.name
153-
permissions = get_permissions(path) if exists(path) else None
154-
os.replace(temp_path, path)
155-
if permissions:
156-
set_permissions(path, permissions)
152+
# file is now closed, safe to replace on Windows
153+
permissions = get_permissions(path) if exists(path) else None
154+
os.replace(temp_path, path)
155+
if permissions:
156+
set_permissions(path, permissions)
157157
except FileNotFoundError:
158158
# success - the NamedTemporaryFile has not been able
159159
# to remove the temp file on __exit__ because the temp file

0 commit comments

Comments
 (0)