0

I have to create a function that reads a random line from a text file in python.

I have the following code but am not able to get it to work

import random

def randomLine(filename):
    #Retrieve a  random line from a file, reading through the file irrespective of the length
    fh = open(filename.txt, "r")
    lineNum = 0
    it = ''

    while 1:
        aLine = fh.readline()
        lineNum = lineNum + 1
        if aLine != "":

            # How likely is it that this is the last line of the file ? 
            if random.uniform(0,lineNum)<1:
                it = aLine
        else:
            break

    fh.close()

    return it
print(randomLine(testfile.txt))

I got so far but,need help to go further, Please help

once the program is running i'm getting an error saying

print(randomLine(testfile.txt))
NameError: name 'testfile' is not defined
lnuwizard
  • 21
  • 4
  • What is the current error or problem you are facing? – OregonTrail Oct 06 '14 at 02:55
  • What is the error? Please paste the stack trace into your question. – OregonTrail Oct 06 '14 at 02:58
  • 1
    `print(randomLine(testfile.txt))` You need quotes around the `testfile.txt`, so that it becomes a string. – Colonel Thirty Two Oct 06 '14 at 03:01
  • Ok, I was wondering if that was due to edits made to your copy-and-paste, but that's the first problem with your code. Filenames are strings, that should be quoted, e.g. `"filename.txt"`. But in the case of your `randomLine` function, you should be using the variable that you passed into the function `filename` (with no quotes). When you invoke the function, you should use quotes, or another filename string, e.g. `print(randomLine("testfile.txt"))` – OregonTrail Oct 06 '14 at 03:01
  • Thank you so much @ColonelThirtyTwo and fixed the silly mistake of not quoting **"filename.txt"** – lnuwizard Oct 06 '14 at 03:13
  • And thank you @OregonTrail , I got he quotes fixed in **"filename.txt"** – lnuwizard Oct 06 '14 at 03:15

1 Answers1

0

Here's a version that's been tested to work, and avoids empty lines.

Variable names are verbose for 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()

    return 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()
OregonTrail
  • 8,594
  • 7
  • 43
  • 58