acclivity

pyNameSelection

Dec 14th, 2021 (edited)
739
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.01 KB | None | 0 0
  1. # An exercise from the Python For Beginners Facebook group
  2. # Read a file of names. Allow the user to choose a name out of a selection of 5 of not previously selected names.
  3. # Write out the file again, with selected names preceded with '##'
  4. from random import *
  5. fin = open("teststuff.txt")
  6. thelist = fin.readlines()           # Read all the lines from the file into a list
  7.  
  8. # split the whole list into two list, already checked (checked), and not yet checked (avail)
  9. # (this could be done more succinctly using List Comprehension, but we'll do it 'long-hand' for now)
  10. avail = []
  11. checked = []
  12. for name in thelist:
  13.     if name.startswith("#"):
  14.         checked.append(name)
  15.     else:
  16.         avail.append(name)
  17.  
  18. select = sample(avail, 5)           # Make a selection of 5 names from the available list
  19.  
  20. for x, name in enumerate(select):           # Print the selected names
  21.     print(x + 1, ":  ", name.strip())       # x is 0 to 4, number to print is 1 to 5
  22.  
  23. while True:
  24.     sel = input("pick a number to check off, or 0 to finish: ")
  25.     if not sel in ['0', '1', '2', '3', '4', '5']:
  26.         print("Invalid selection. Try again\n")
  27.         continue
  28.     if sel == "0":          # User wishes to terminate the script
  29.         break
  30.     x = int(sel)
  31.     name = select[x-1]      # the index into the list is 1 less than the number associated with a name
  32.     print(name.strip(), "has been checked")     # print name without \n
  33.     checked.append("##" + name)                 # put this name on the checked list, start with ##
  34.     avail.remove(name)                          # remove this name from the available list
  35.  
  36. fin.close()
  37.  
  38. fout = open("teststuff.txt", "w")               # Re-open the file, this time as output
  39. for name in checked:                            # First write out all the checked names
  40.     fout.write(name)
  41. for name in avail:                              # Then write out all the still available names
  42.     fout.write(name)
  43.  
  44. fout.close()            # seems this is needed, ... for "Idle" at least
  45.  
  46.  
Add Comment
Please, Sign In to add comment