Randomly selecting lines from files

后端 未结 7 679
轮回少年
轮回少年 2021-01-13 14:21

I have bunch of files and very file has a header of 5 lines. In the rest of the file, pair of line form an entry. I need to randomly select entry from these files. How can

7条回答
  •  执念已碎
    2021-01-13 14:56

    Another Python option; reading the contents of all files into memory:

    import random
    import fileinput
    
    def openhook(filename, mode):
        f = open(filename, mode)
        headers = [f.readline() for _ in range(5)]
        return f
    
    num_entries = 3
    lines = list(fileinput.input(openhook=openhook))
    print random.sample(lines, num_entries)
    

提交回复
热议问题