[Tutor] Can tempfile.NamedTemporaryFile(delete=False) be used to create *permanent* uniquely named files?

Peter Otten __peter__ at web.de
Tue Oct 23 05:24:28 EDT 2018


Cameron Simpson wrote:

> On 21Oct2018 10:55, Peter Otten <__peter__ at web.de> wrote:
>>boB Stepp wrote:
>>> So I am now wondering if using
>>> tempfile.NamedTemporaryFile(delete=False) would solve this problem
>>> nicely?  As I am not very familiar with this library, are there any
>>> unforeseen issues I should be made aware of?  Would this work equally
>>> well on all operating systems?
>>
>>I think this is cool thinking outside of the box.
>>
>>I would not have "dared" this, but now you suggest it I cannot see
>>anything wrong with your approach.
> 
> The doco for mktemp (do not use! use mkstemp or the NamedTemporaryFile
> classes instead!) explicitly mentions using delete=False.

Well, "permanent temporary file" does sound odd.

By the way, NamedTemporaryFile returns a proxy instead of the file itself. 
In some rare cases that could be a problem.

Would mktemp() really be dangerous if you used it like this,

def new_game(directory):
    for _retry in range(3):
        filename = mktemp("game_", ".json", dir=directory)
        try:
           return open(filename, "x")
        except FileExistsError:
           pass
    raise FileExistsError


with the "x" mode?

        




More information about the Tutor mailing list