-
Notifications
You must be signed in to change notification settings - Fork 25
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Manipulate with tempfiles after they are closed (#139)
* Manipulate with tempfiles after they are closed Fixes: #135 * CloseableTemporaryFile: close a file before unlink (if not closed yet)
- Loading branch information
Showing
6 changed files
with
36 additions
and
15 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,6 +1,24 @@ | ||
import os | ||
import tempfile | ||
from contextlib import contextmanager | ||
|
||
|
||
def is_readable_file(filename): | ||
try: | ||
open(filename).read() | ||
return True | ||
except UnicodeDecodeError: | ||
return False | ||
|
||
|
||
# TODO: use tempfile.NamedTemporaryFile(delete_on_close=False) since Python 3.12 is the oldest supported release | ||
@contextmanager | ||
def CloseableTemporaryFile(mode='w+b', dir=None): | ||
f = tempfile.NamedTemporaryFile(mode=mode, delete=False, dir=dir) | ||
try: | ||
yield f | ||
finally: | ||
# For Windows systems, be sure we always close the file before we remove it! | ||
if not f.closed: | ||
f.close() | ||
os.remove(f.name) |