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()
- import random
- def choose_line(file_name):
- """Choose a line at random from the text file"""
- with open(file_name, 'r') as file:
- lines = file.readlines()
- random_line = random.choice(lines)
- 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
- def choose_line_big_file(file_name):
- """Choose a line at random from the a big file"""
- line_pos = {}
- with open(file_name, 'r') as file:
- # Count the number of lines & record their position
- for line_count in itertools.count():
- file_pos = file.tell()
- line = file.readline()
- if not line:
- break
- line_pos[line_count] = file_pos
- # Choose a line number
- chosen_line = random.randint(0, line_count-1)
- # Go to the start of the chosen line.
- file.seek(line_pos[chosen_line])
- line = file.readline()
- 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