QNA > H > How To Randomly Choose A Line From A Txt File In Python 3

How to randomly choose a line from a TXT file in Python 3

You don’t say how big the file is.

If it is relatively small - read the whole file in (using readlines(), and then use random.choice()

  1. import random 
  2.  
  3. def choose_line(file_name): 
  4. """Choose a line at random from the text file""" 
  5. with open(file_name, 'r') as file: 
  6. lines = file.readlines() 
  7. random_line = random.choice(lines) 
  8. return random_line 

If the file is too big to read the entire thing into memory - then I would suggest a three step process - 1st identify the number of lines in the files and record their positions in the file, 2nd choose a random number corresponding to the number of lines - 3rd - pick out that line

  1. def choose_line_big_file(file_name): 
  2. """Choose a line at random from the a big file"""  
  3.  
  4. line_pos = {} 
  5.  
  6. with open(file_name, 'r') as file: 
  7. # Count the number of lines & record their position 
  8. for line_count in itertools.count(): 
  9. file_pos = file.tell() 
  10. line = file.readline() 
  11. if not line: 
  12. break 
  13. line_pos[line_count] = file_pos 
  14.  
  15. # Choose a line number 
  16. chosen_line = random.randint(0, line_count-1) 
  17.  
  18. # Go to the start of the chosen line. 
  19. file.seek(line_pos[chosen_line]) 
  20. line = file.readline() 
  21. return line 

If this is something that needs to be done regularly with an single program then opening, reading and close the file repeatedly might be wasteful - so some method of caching some of the results might be considered.

Disclaimer : Neither solution has been fully tested

Di Jacobo

Una xbox one potrebbe funzionare bene per il mining di Bitcoin? :: Come mai la gente viene giudicata perché guarda gli anime?
Link utili