I am trying to make a lottery program for my school (we have an economic system).
My program generates numbers and saves it off into a text file. When I want to "pull" numbers out of my generator I want it to ensure that there is a winner.
Q: How do I have Python select a random line out of my text file and give my output as that number?
Fetch a random line from a text file in C++ Save the file in the same directory as the program. Use ifstream to operate on the file. Include fstream header to use this. Call the function srand() with argument 'time(0)' or 'time(NULL)' to make sure rand() function returns different random number for each call.
Use readlines() to Read the range of line from the File The readlines() method reads all lines from a file and stores it in a list. You can use an index number as a line number to extract a set of lines from it. This is the most straightforward way to read a specific line from a file in Python.
How to Create Files in Python. In Python, you use the open() function with one of the following options – "x" or "w" – to create a new file: "x" – Create: this command will create a new file if and only if there is no file already in existence with that name or else it will return an error.
def random_line():
line_num = 0
selected_line = ''
with open(filename) as f:
while 1:
line = f.readline()
if not line: break
line_num += 1
if random.uniform(0, line_num) < 1:
selected_line = line
return selected_line.strip()
Although most of the approaches given here would work, but they tend to load the whole file in the memory at once. But not this approach. So even if the files are big, this would work.
The approach is not very intuitive at first glance. The theorem behind this states that when we have seen N lines in there is a probability of exactly 1/N that each of them is selected so far.
From Page no 123 of 'Python Cookbook'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With