我是新手Python程序员(通过CodeAcademy课程学习),需要一些帮助来解决这个问题。
我有一个文件,“TestingDeleteLines.txt”,大约有300行文本。现在,我正在尝试从该文件中打印出10行随机行,然后删除这些行。
因此,如果我的文件有10行:
Carrot
Banana
Strawberry
Canteloupe
Blueberry
Snacks
Apple
Raspberry
Papaya
Watermelon
我需要它从这些行中随机选出一个,告诉我它随机选出了蓝莓、胡萝卜、西瓜和香蕉,然后删除这些行。
问题在于,当Python读取文件时,它会读取该文件,一旦到达结尾,就不会返回并删除这些行。我目前的想法是将这些行写入列表,然后重新打开文件,将列表与文本文件匹配,如果找到匹配项,则删除这些行。
我目前的问题有两个:
- It's duplicating the random elements. If it picks a line, I need it to not pick that same line again. However, using
random.sample
doesn't seem to work, as I need those lines separated out when I later use each line to append to a URL. I don't feel like my logic (write to array->find matches in text file->delete) is the most ideal logic. Is there a better way to write this?
import webbrowser import random """url= 'http://www.google.com' webbrowser.open_new_tab(url+myline)""" Eventually, I need a base URL + my 10 random lines opening in each new tab def ShowMeTheRandoms(): x=1 DeleteList= [] lines=open('TestingDeleteLines.txt').read().splitlines() for x in range(0,10): myline=random.choice(lines) print(myline) """debugging, remove later""" DeleteList.append(myline) x=x+1 print DeleteList """debugging, remove later""" ShowMeTheRandoms()
readlines()
读入所有行,关闭文件,然后重新写入整个文件。 - Morgan Thrappfile_object.seek(0)
应该让您再次从开头开始迭代。在您的示例中,lines
看起来像是一个file_object。 - wwii