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

前端 未结 6 1599
礼貌的吻别
礼貌的吻别 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条回答
  •  萌比男神i
    2020-11-30 13:44

    Lets assume you have a list of lines from your file stored in items

    >>> items = ['a', 'b', 'c', 'd', 'e', 'f']
    >>> choices = random.sample(items, 2)  # select 2 items
    >>> choices  # here are the two
    ['b', 'c']
    >>> for i in choices:
    ...   items.remove(i)
    ...
    >>> items  # tee daa, no more b or c
    ['a', 'd', 'e', 'f']
    

    From here you would overwrite your previous text file with the contents of items joining with your preferred line ending \r\n or \n. readlines() does not strip line endings so if you use that method, you do not need to add your own line endings.

提交回复
热议问题