Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on Jul 14th, 2012  |  syntax: None  |  size: 0.96 KB  |  hits: 13  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. Best way to generate random file names in Python
  2. In [4]: import tempfile
  3.        
  4. In [5]: tf = tempfile.NamedTemporaryFile()
  5. In [6]: tf.name
  6. Out[6]: 'c:\blabla\locals~1\temp\tmptecp3i'
  7.  
  8. In [7]: tf = tempfile.NamedTemporaryFile()
  9. In [8]: tf.name
  10. Out[8]: 'c:\blabla\locals~1\temp\tmpr8vvme'
  11.        
  12. tempfile.NamedTemporaryFile([mode='w+b'[, bufsize=-1[, suffix=''[, prefix='tmp'[, dir=None[, delete=True]]]]]])
  13.        
  14. In [9]: tf = tempfile.NamedTemporaryFile(prefix="zz")
  15. In [10]: tf.name
  16. Out[10]: 'c:\blabla\locals~1\temp\zzrc3pzk'
  17.        
  18. import uuid
  19. filename = str(uuid.uuid4())
  20.        
  21. def add_prefix(filename):
  22.  
  23.   from hashlib import md5
  24.   from time import localtime
  25.  
  26.   return "%s_%s" % (md5(str(localtime())).hexdigest(), filename)
  27.        
  28. a38ff35794ae366e442a0606e67035ba_style.css
  29. 7a5f8289323b0ebfdbc7c840ad3cb67b_style.css
  30.        
  31. import datetime
  32. basename = "mylogfile"
  33. suffix = datetime.datetime.now().strftime("%y%m%d_%H%M%S")
  34. filename = "_".join([basename, suffix]) # e.g. 'mylogfile_120508_171442'