Python: How to create a unique file name?

I have a python web form with two parameters - Upload files and textarea . I need to take values ​​from each and pass them to another command line program. I can easily pass the file name with file upload options, but I'm not sure how to pass the value of the text field.

I think I need to do:

  • Create a unique file name
  • Create a temporary file with this name in the working directory
  • Save values ​​passed from text field to temporary file
  • Run command line program from my python module and pass it the name of the temporary file

I am not sure how to create a unique file name. Can someone give me some tips on how to create a unique file name? Any algorithms, sentences and lines of code are appreciated.

thanks for the concern

+82
python file unique
Jun 02 '10 at 20:53 on
source share
8 answers

I did not think your question is very clear, but if you only need a unique file name ...

import uuid unique_filename = str(uuid.uuid4()) 
+127
Jun 02 '10 at
source share

If you want to create temporary files in Python, there is a module called tempfile in the standard Python libraries. If you want to run other programs to work with the file, use tempfile.mkstemp () to create the files and os.fdopen () to access the file descriptors that mkstemp () provides.

By the way, you say that you use commands from the Python program? You will almost certainly use the subprocess module.

So you can pretty fun write code that looks like this:

 import subprocess import tempfile import os (fd, filename) = tempfile.mkstemp() try: tfile = os.fdopen(fd, "w") tfile.write("Hello, world!\n") tfile.close() subprocess.Popen(["/bin/cat", filename]).wait() finally: os.remove(filename) 

By running this, you should find that the cat worked fine, but the temporary file was deleted in the finally block. Keep in mind that you need to delete the temporary file that mkstemp () returns on its own - the library does not know when you are done with it!

(Edit: I suggested that NamedTemporaryFile did exactly what you need, but it may not be so convenient - the file is deleted immediately when the temp file object is closed, and other processes open the file before it is closed, it will not work on some platforms, in particular Windows. Sorry, not on my part.)

+50
Jun 02 '10 at
source share

The uuid module would be a good choice, I prefer to use uuid.uuid4().hex as an arbitrary file name because it will return the sixth line without a dash .

 import uuid filename = uuid.uuid4().hex 

The outputs should look like this:

 >>> import uuid >>> uuid.uuid() UUID('20818854-3564-415c-9edc-9262fbb54c82') >>> str(uuid.uuid4()) 'f705a69a-8e98-442b-bd2e-9de010132dc4' >>> uuid.uuid4().hex '5ad02dfb08a04d889e3aa9545985e304' # <-- this one 
+24
Jul 09 '17 at 1:53 on
source share

Perhaps you need a unique temporary file?

 import tempfile f = tempfile.NamedTemporaryFile(mode='w+b', delete=False) print f.name f.close() 

f file is open. delete=False means do not delete the file after closing.

+13
18 sept. '14 at 12:22
source share

You can use the datetime module

 import datetime uniq_filename = str(datetime.datetime.now().date()) + '_' + str(datetime.datetime.now().time()).replace(':', '.') 

Please note: I use replace because colons are not allowed in file names on many operating systems.

Here it is, it will give you a unique file name every time.

+6
May 26 '17 at 10:00
source share

I came across this question and I will add my solution for those who may be looking for something similar. My approach was to create an arbitrary file name from ascii characters. It will be unique with a good probability.

 from random import sample from string import digits, ascii_uppercase, ascii_lowercase from tempfile import gettempdir from os import path def rand_fname(suffix, length=8): chars = ascii_lowercase + ascii_uppercase + digits fname = path.join(gettempdir(), 'tmp-' + ''.join(sample(chars, length)) + suffix) return fname if not path.exists(fname) \ else rand_fname(suffix, length) 
+1
Apr 01 '13 at 15:16
source share

This can be done using a unique function in the ufp.path module.

 import ufp.path ufp.path.unique('./test.ext') 

if the current path exists, the file is 'test.ext'. The ufp.path.unique function returns './test (d1) .ext'.

0
Mar 22 '15 at 7:26
source share

To create a unique file path, if one exists, use a random package to create a new line name for the file. You can refer to the code below for the same.

 import os import random import string def getUniquePath(folder, filename): path = os.path.join(folder, filename) while os.path.exists(path): path = path.split('.')[0] + ''.join(random.choice(string.ascii_lowercase) for i in range(10)) + '.' + path.split('.')[1] return path 

Now you can use this path to create the file accordingly.

0
Sep 05 '19 at 6:31
source share



All Articles