Home > Enterprise >  Python def to read random line from file
Python def to read random line from file

Time:07-01

I want to create a class with function to read random lines from a file but i don't really know how to do it.

I am very new to python and this is the best I could come up with

code:

    from random import randrange

class File:

    def __init__(self):
        self.fl = None

    def ran_sel(self, fl):
        self.fl = fl
        flr = open(fl, "r")
        names = flr.splitlines()
        length = int(len(names))
        sel_name = names[randrange(length)]
        print(sel_name)


File.ran_sel(Names.txt)

CodePudding user response:

Read the file into an array. Now you can pick items from the array at random.

import random

class File:
    def __init__(self,name):
        self.lines = open(name).readlines()

    def ran_sel(self):
        return random.choice(self.lines)

f = File('Names.txt')
print(f.ran_sel())
print(f.ran_sel())
  • Related