Python: Choose random line from file, then delete that line

前端 未结 6 1605
礼貌的吻别
礼貌的吻别 2020-11-30 13:16

I\'m new to Python (in that I learned it through a CodeAcademy course) and could use some help with figuring this out.

I have a file, \'TestingDeleteLines.txt\', tha

6条回答
  •  鱼传尺愫
    2020-11-30 13:46

    I have a file, 'TestingDeleteLines.txt', that's about 300 lines of text. Right now, I'm trying to get it to print me 10 random lines from that file, then delete those lines.

    #!/usr/bin/env python
    import random
    
    k = 10
    filename = 'TestingDeleteLines.txt'
    with open(filename) as file:
        lines = file.read().splitlines()
    
    if len(lines) > k:
        random_lines = random.sample(lines, k)
        print("\n".join(random_lines)) # print random lines
    
        with open(filename, 'w') as output_file:
            output_file.writelines(line + "\n"
                                   for line in lines if line not in random_lines)
    elif lines: # file is too small
        print("\n".join(lines)) # print all lines
        with open(filename, 'wb', 0): # empty the file
            pass
    

    It is O(n**2) algorithm that can be improved if necessary (you don't need it for a tiny file such as your input)

提交回复
热议问题