简体   繁体   中英

Python def to read random line from file

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)

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())

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM