How do I read a random line from one file?

前端 未结 11 831
灰色年华
灰色年华 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:20

    import random
    
    with open("file.txt", "r") as f:
        lines = f.readlines()
        print (random.choice(lines))
    

提交回复
热议问题