How do I read a random line from one file?

前端 未结 11 797
灰色年华
灰色年华 2020-12-04 20:03

Is there a built-in method to do it? If not how can I do this without costing too much overhead?

11条回答
  •  天命终不由人
    2020-12-04 20:10

    You can add the lines into a set() which will change their order randomly.

    filename=open("lines.txt",'r')
    f=set(filename.readlines())
    filename.close()
    

    To find the 1st line:

    print(next(iter(f)))
    

    To find the 3rd line:

    print(list(f)[2])
    

    To list all the lines in the set:

    for line in f:
        print(line)
    

提交回复
热议问题