Skip to content

Commit cece6e7

Browse files
committed
Clearer implementation of rewrite, and ensure that dest is always flushed and closed.
1 parent a26a055 commit cece6e7

File tree

1 file changed

+10
-13
lines changed

1 file changed

+10
-13
lines changed

src/dotenv/main.py

Lines changed: 10 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -125,20 +125,17 @@ def rewrite(
125125
path: Union[str, os.PathLike],
126126
encoding: Optional[str],
127127
) -> Iterator[Tuple[IO[str], IO[str]]]:
128-
dest = None
129-
try:
130-
if not os.path.isfile(path):
131-
with open(path, "w+", encoding=encoding) as source:
132-
source.write("")
133-
dest = tempfile.NamedTemporaryFile(mode="w+", delete=False, encoding=encoding)
134-
with open(path, encoding=encoding) as source:
135-
yield (source, dest) # type: ignore
136-
except BaseException:
137-
if dest and os.path.isfile(dest.name):
128+
if not os.path.isfile(path):
129+
with open(path, mode="w", encoding=encoding) as source:
130+
source.write("")
131+
with tempfile.NamedTemporaryFile(mode="w", encoding=encoding, delete=False) as dest:
132+
try:
133+
with open(path, encoding=encoding) as source:
134+
yield (source, dest)
135+
except BaseException:
138136
os.unlink(dest.name)
139-
raise
140-
else:
141-
shutil.move(dest.name, path)
137+
raise
138+
shutil.move(dest.name, path)
142139

143140

144141
def set_key(

0 commit comments

Comments
 (0)