i'm new python (in learned through codeacademy course) , use figuring out.
i have file, 'testingdeletelines.txt', that's 300 lines of text. right now, i'm trying print me 10 random lines file, delete lines.
so if file has 10 lines:
carrot
banana
strawberry
canteloupe
blueberry
snacks
apple
raspberry
papaya
watermelon
i need randomly pick out lines, tell me it's randomly picked blueberry, carrot, watermelon, , banana, , delete lines.
the issue is, when python reads file, reads file , once gets end, won't go , delete lines. current thinking write lines list, reopen file, match list text file, , if finds match, delete lines.
my current problem twofold:
- it's duplicating random elements. if picks line, need not pick same line again. however, using random.sample doesn't seem work, need lines separated out when later use each line append url.
i don't feel logic (write array->find matches in text file->delete) ideal logic. there better way write this?
import webbrowser import random """url= 'http://www.google.com' webbrowser.open_new_tab(url+myline)""" eventually, need base url + 10 random lines opening in each new tab def showmetherandoms(): x=1 deletelist= [] lines=open('testingdeletelines.txt').read().splitlines() 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()
i have file, 'testingdeletelines.txt', that's 300 lines of text. right now, i'm trying print me 10 random lines file, delete lines.
#!/usr/bin/env python import random k = 10 filename = 'testingdeletelines.txt' open(filename) file: lines = file.read().splitlines() if len(lines) > k: random_lines = random.sample(lines, k) print("\n".join(random_lines)) # print random lines open(filename, 'w') output_file: output_file.writelines(line + "\n" line in lines if line not in random_lines) elif lines: # file small print("\n".join(lines)) # print lines open(filename, 'wb', 0): # empty file pass
it o(n**2)
algorithm can improved if necessary (you don't need tiny file such input)
Comments
Post a Comment