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', 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.
So if my file has 10 lines:
Carrot
Banana
Strawberry
Canteloupe
Blueberry
Snacks
Apple
Raspberry
Papaya
Watermelon
I need it to randomly pick out from those lines, tell me it's randomly picked blueberry, carrot, watermelon, and banana, and then delete those lines.
The issue is, when Python reads a file, it reads that file and once it gets to the end, it won't go back and delete the lines. My current thinking was that I could write the lines to a list, then reopen the file, match the list to the text file, and if it finds a match, delete the lines.
My current problem is twofold:
- 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()
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…