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

前端 未结 6 1609
礼貌的吻别
礼貌的吻别 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:45

    Maybe you could try generating 10 random numbers from 0 to 300 using

    deleteLineNums = random.sample(xrange(len(lines)), 10)
    

    and then delete from the lines array by making a copy with list comprehensions:

    linesCopy = [line for idx, line in enumerate(lines) if idx not in deleteLineNums]
    lines[:] = linesCopy
    

    And then writing lines back to 'TestingDeleteLines.txt'.

    To see why the copy code above works, this post might be helpful:

    Remove items from a list while iterating

    EDIT: To get the lines at the randomly generated indices, simply do:

    actualLines = []
    for n in deleteLineNums:
        actualLines.append(lines[n])
    

    Then actualLines contians the actual line text of the randomly generated line indices.

    EDIT: Or even better, use a list comrehension:

    actualLines = [lines[n] for n in deleteLineNums]
    

提交回复
热议问题