How do I read a random line from one file?

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

    It depends what do you mean by "too much" overhead. If storing whole file in memory is possible, then something like

    import random
    
    random_lines = random.choice(open("file").readlines())
    

    would do the trick.

提交回复
热议问题