Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # An exercise from the Python For Beginners Facebook group
- # Read a file of names. Allow the user to choose a name out of a selection of 5 of not previously selected names.
- # Write out the file again, with selected names preceded with '##'
- from random import *
- fin = open("teststuff.txt")
- thelist = fin.readlines() # Read all the lines from the file into a list
- # split the whole list into two list, already checked (checked), and not yet checked (avail)
- # (this could be done more succinctly using List Comprehension, but we'll do it 'long-hand' for now)
- avail = []
- checked = []
- for name in thelist:
- if name.startswith("#"):
- checked.append(name)
- else:
- avail.append(name)
- select = sample(avail, 5) # Make a selection of 5 names from the available list
- for x, name in enumerate(select): # Print the selected names
- print(x + 1, ": ", name.strip()) # x is 0 to 4, number to print is 1 to 5
- while True:
- sel = input("pick a number to check off, or 0 to finish: ")
- if not sel in ['0', '1', '2', '3', '4', '5']:
- print("Invalid selection. Try again\n")
- continue
- if sel == "0": # User wishes to terminate the script
- break
- x = int(sel)
- name = select[x-1] # the index into the list is 1 less than the number associated with a name
- print(name.strip(), "has been checked") # print name without \n
- checked.append("##" + name) # put this name on the checked list, start with ##
- avail.remove(name) # remove this name from the available list
- fin.close()
- fout = open("teststuff.txt", "w") # Re-open the file, this time as output
- for name in checked: # First write out all the checked names
- fout.write(name)
- for name in avail: # Then write out all the still available names
- fout.write(name)
- fout.close() # seems this is needed, ... for "Idle" at least
Add Comment
Please, Sign In to add comment