[Tutor] Can tempfile.NamedTemporaryFile(delete=False) be used to create *permanent* uniquely named files?
robertvstepp at gmail.com
Sun Oct 21 03:04:05 EDT 2018
On Sun, Oct 21, 2018 at 1:47 AM Quentin Agren <quentin.agren at gmail.com> wrote:
> 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 am planning to set both the "dir" and "suffix" parameters if I go
this route and probably the "mode" parameter, too.
> - 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)
It is important for me to have no name collisions however unlikely
such an event might be.
> import random
> CHARS = 'abcdefghijklmnopqrstuvw1234567890'
> def random_name(length):
> return ''.join([random.choice(CHARS) for _ in range(length)])
It occurred to me to do this type of approach. But why write this
myself when a standard library module may give me what I want with
only one or two lines of code? When I searched online others have
recommended using the uuid library to generate names. But one still
has to check that it does not already exist (However unlikely.) and
format the final filename. And I would have to do the same for the
code snippet you supplied, adding a few additional lines of code.
But thank you for your input! It may turn out that there is something
undesirable that I am unaware of in the NamedTemporaryFile approach,
other than what I really want is a NamedPermanentFile approach, but
the standard library naming suggest otherwise! ~(:>))
More information about the Tutor