aleatory_file_name.py 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. import os
  2. import string
  3. class aleatory_file_name:
  4. """
  5. That create new random file name, with given size and given extension.
  6. File name is returned as a string. Creating new instance of that class
  7. does not return an instance, but only string result.
  8. """
  9. def __new__(cls, extension: str = "", size: int = 32) -> str:
  10. """
  11. That create new random file name from system random number
  12. generator, extension and size. Resulted file name have given size,
  13. given extension but name is fully random. Name could contain small
  14. letters, big letters and digits.
  15. Parameters
  16. ----------
  17. extension : str (default: "")
  18. Extension of the file.
  19. size : int (default: 32)
  20. Lenght of the file name.
  21. Returns
  22. -------
  23. str
  24. Random name of the file.
  25. """
  26. name_lenght = size
  27. if len(extension) > 0:
  28. name_lenght -= 1 + len(extension)
  29. name = cls.__get_random_name(name_lenght)
  30. return cls.__get_file_name(name, extension)
  31. @classmethod
  32. def __get_chars(cls) -> str:
  33. """
  34. It return full aphabet with small and big letters. To letters it
  35. add also digits.
  36. Returns
  37. -------
  38. str
  39. Full alphabet with digits, big and small letters.
  40. """
  41. return str(string.ascii_letters + string.digits)
  42. @classmethod
  43. def __get_random_name(cls, size: int) -> str:
  44. """
  45. That generate random name (random string wich letters from alphabet
  46. generated in __get_chars) with size passed by intiger parameter.
  47. Parameters
  48. ----------
  49. size : int
  50. Lenght of random name.
  51. Returns
  52. -------
  53. str
  54. Random name with given lenght.
  55. """
  56. chars = cls.__get_chars()
  57. result = str()
  58. for count in range(size):
  59. random = os.urandom(1)[0]
  60. random = random % len(chars)
  61. result = result + chars[random]
  62. return result
  63. @classmethod
  64. def __get_file_name(cls, name: str, extension: str) -> str:
  65. """
  66. That create file name from name and extension. When extension is
  67. blank, then it return file name without extension. When extension
  68. is passed then return file name as "name.extension".
  69. Parameters
  70. ----------
  71. name : str
  72. Name of the file.
  73. extensions : str
  74. Extension of the file.
  75. Returns
  76. -------
  77. str
  78. Full file name from name and extension.
  79. """
  80. if len(extension) > 0:
  81. return name + "." + extension
  82. return name