Skip to content

Commit 6ff1391

Browse files
authored
Fix temporary file is deleted before closing, in the rewrite function (#468)
Currently, if an error is raised while using files from the rewrite function, then the temporary file is deleted before closing it. This is okay on unix, but unlinking open files causes an error on Windows.
1 parent 0b94ac0 commit 6ff1391

File tree

1 file changed

+12
-7
lines changed

1 file changed

+12
-7
lines changed

src/dotenv/main.py

Lines changed: 12 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import io
22
import logging
33
import os
4+
import pathlib
45
import shutil
56
import sys
67
import tempfile
@@ -131,17 +132,21 @@ def rewrite(
131132
path: StrPath,
132133
encoding: Optional[str],
133134
) -> Iterator[Tuple[IO[str], IO[str]]]:
134-
if not os.path.isfile(path):
135-
with open(path, mode="w", encoding=encoding) as source:
136-
source.write("")
135+
pathlib.Path(path).touch()
136+
137137
with tempfile.NamedTemporaryFile(mode="w", encoding=encoding, delete=False) as dest:
138+
error = None
138139
try:
139140
with open(path, encoding=encoding) as source:
140141
yield (source, dest)
141-
except BaseException:
142-
os.unlink(dest.name)
143-
raise
144-
shutil.move(dest.name, path)
142+
except BaseException as err:
143+
error = err
144+
145+
if error is None:
146+
shutil.move(dest.name, path)
147+
else:
148+
os.unlink(dest.name)
149+
raise error from None
145150

146151

147152
def set_key(

0 commit comments

Comments
 (0)