fork download
  1. import array
  2. import os
  3. import random
  4.  
  5.  
  6. class YobaRandom:
  7. SIZE_LIMIT = 640 * 1024
  8.  
  9. def __init__(self, file):
  10. fsize = os.path.getsize(file)
  11. self.bigfile = fsize > self.SIZE_LIMIT
  12. fh = open(file, encoding='utf=8', newline='')
  13. if self.bigfile:
  14. arr = array.array('L')
  15. offset = 0
  16. for line in fh:
  17. arr.append(offset)
  18. offset += len(line)
  19. self.fh = fh
  20. self.indexes = arr
  21. else:
  22. self.values = [val.rstrip() for val in fh]
  23. fh.close()
  24.  
  25. def __del__(self):
  26. if self.bigfile:
  27. self.fh.close()
  28.  
  29. def choice(self):
  30. if self.bigfile:
  31. idx = random.randint(0, len(self.indexes) - 1)
  32. offset = self.indexes[idx]
  33. self.fh.seek(offset)
  34. return self.fh.readline().rstrip()
  35. else:
  36. return random.choice(self.values)
  37.  
  38.  
  39. yr = YobaRandom('list.txt')
  40. print(yr.choice())
  41.  
Runtime error #stdin #stdout #stderr 0.21s 23512KB
stdin
Standard input is empty
stdout
Standard output is empty
stderr
Traceback (most recent call last):
  File "./prog.py", line 39, in <module>
  File "./prog.py", line 10, in __init__
  File "/usr/lib/python3.7/genericpath.py", line 50, in getsize
    return os.stat(filename).st_size
FileNotFoundError: [Errno 2] No such file or directory: 'list.txt'
Exception ignored in: <function YobaRandom.__del__ at 0x7f0652895f28>
Traceback (most recent call last):
  File "./prog.py", line 26, in __del__
AttributeError: 'YobaRandom' object has no attribute 'bigfile'