How do I read a random line from one file?

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

    import random
    lines = open('file.txt').read().splitlines()
    myline =random.choice(lines)
    print(myline)
    

    For very long file: seek to random place in file based on it's length and find two newline characters after position (or newline and end of file). Do again 100 characters before or from beginning of file if original seek position was <100 if we ended up inside the last line.

    However this is over complicated, as file is iterator.So make it list and take random.choice (if you need many, use random.sample):

    import random
    print(random.choice(list(open('file.txt'))))
    

提交回复
热议问题