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

Quentin Agren quentin.agren at gmail.com
Sun Oct 21 02:47:28 EDT 2018

Hi Robert,

Far from being an expert, my two cents on this:

- As I understand it, you should at least use the 'dir' parameter to
NamedTemporaryFile,  otherwise your files will be created in a '/tmp/'-like
directory that may be wiped clean by the OS now and then.
- I seems that the only functionality you desire from tempfile is the
generation of a random file name (and maybe ensuring that no collision
occurs). You could use the 'random' standard library module to generate
such names easily (which is about what tempfile does under the hood)

import random
CHARS = 'abcdefghijklmnopqrstuvw1234567890'
def random_name(length):
    return ''.join([random.choice(CHARS) for _ in range(length)])


Le dim. 21 oct. 2018 à 08:15, boB Stepp <robertvstepp at gmail.com> a écrit :

> Use case:  I want to allow a user of my Solitaire Scorekeeper program
> to be able to give any name he wants to each game of solitaire he
> wishes to record.  My thought for permanent storage of each game's
> parameters is to use a dictionary to map the user-chosen game names to
> a unique json filename.  This way I hope no shenanigans can occur with
> weird characters/non-printing characters.
> My initial thought was to just have a sequence of game names with
> incrementing numerical suffixes:  game_0, game_1, ... , game_n.  But
> this would require the program to keep track of what the next
> available numerical suffix is.  Additionally, if a user chooses to
> delete a game, then there would be a gap in the numerical sequence of
> the game filenames.  I find such a gap aesthetically displeasing and
> would probably go to additional efforts to reuse such deleted
> filenames, so there would be no such "gaps".
> 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?
> TIA!
> --
> boB
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor

More information about the Tutor mailing list