How do I read a random line from one file?

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

    This may be bulky, but it works I guess? (at least for txt files)

    import random
    choicefile=open("yourfile.txt","r")
    linelist=[]
    for line in choicefile:
        linelist.append(line)
    choice=random.choice(linelist)
    print(choice)
    

    It reads each line of a file, and appends it to a list. It then chooses a random line from the list. If you want to remove the line once it's chosen, just do

    linelist.remove(choice)
    

    Hope this may help, but at least no extra modules and imports (apart from random) and relatively lightweight.

提交回复
热议问题