Tuesday, 15 June 2010

python - Function to randomly read a line from a text file -



python - Function to randomly read a line from a text file -

i have create function reads random line text file in python.

i have next code not able work

import random def randomline(filename): #retrieve random line file, reading through file irrespective of length fh = open(filename.txt, "r") linenum = 0 = '' while 1: aline = fh.readline() linenum = linenum + 1 if aline != "": # how lastly line of file ? if random.uniform(0,linenum)<1: = aline else: break fh.close() homecoming print(randomline(testfile.txt))

i got far but,need help go further, please help

once programme running i'm getting error saying

print(randomline(testfile.txt)) nameerror: name 'testfile' not defined

here's version that's been tested work, , avoids empty lines.

variable names verbose clarity.

import random import sys def random_line(file_handle): lines = file_handle.readlines() num_lines = len(lines) random_line = none while not random_line: random_line_num = random.randint(0, num_lines - 1) random_line = lines[random_line_num] random_line = random_line.strip() homecoming random_line file_handle = none if len(sys.argv) < 2: sys.stderr.write("reading stdin\n") file_handle = sys.stdin else: file_handle = open(sys.argv[1]) print(random_line(file_handle)) file_handle.close()

python function random text-files

No comments:

Post a Comment