3

I have to store some temporary files (it does not have to be human-readable). Since I'm creating them from different threads, I don't want to do difficult communication between threads - which name is reserved or already used etc.

The best option seems to be using hash.

Example:

I have many records under the block 'Žilina', '54845'. I want to store them temporary into some txt file.

So I would do this:

write_into_temp_file(name_of_the_file=hashlib.file_name_hash('Žilina54845'))

And I can be sure (99.9999 %) that there won't be any collision with another temporary file.

I've tried to find some inspiration in this question Short Python alphanumeric hash with minimal collisions but those hashes contains signs which are not allowed to be a part of the file name. For example ==

EDIT:

My OS is Windows

Community
  • 1
  • 1
Milano
  • 18,048
  • 37
  • 153
  • 353

1 Answers1

2

Normally hash is not containing any special character...

from hashlib import sha512
import base64

my_file_name="myfilenameverylongtohide.myextension"
hash_filename= sha512(my_file_name).hexdigest()

print hash_filename

>>> e4cd8ae2b7a1c0eb44a987f5b89e43b892709a4b9a072b0fa579715da5becf40318cbc972131485f2132209a76a0ffc199973072665c639d628f641c8b872c8

If you definitely prefer to use base64 notation you may replace the "=" (last character) by "

b64_hash_filename= base64.b64encode(hash_filename).replace('=','')
print b64_hash_filename

>>> YWU0Y2Q4YWUyYjdhMWMwZWI0NGE5ODdmNWI4OWU0M2I4OTI3MDlhNGI5YTA3MmIwZmE1Nzk3MTVkYTViZWNmNDAzMThjYmM5NzIxMzE0ODVmMjEzMjIwOWE3NmEwZmZjMTk5OTczMDcyNjY1YzYzOWQ2MjhmNjQxYzhiODcyYzg
Mogsdad
  • 44,709
  • 21
  • 151
  • 275
A. STEFANI
  • 6,707
  • 1
  • 23
  • 48