Advertisement
HJ50

Nursery rhymes

Apr 2nd, 2020
153
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.21 KB | None | 0 0
  1. '''
  2. Nursery rhyme
  3. When called, displays a nursery rhyme
  4. These are stored in txt files in sub-folder "rhymes"
  5. '''
  6. from os import listdir
  7. from sys import exit
  8.  
  9. def show_rhyme():
  10.     try:
  11.         files=listdir("rhymes")         #sub folder of programs folder
  12.     except:
  13.         print("'rhymes' folder/files not found")
  14.         sys.exit(0)
  15.    
  16.     for i, val in enumerate(files):
  17.         print(i+1,val[0:-4])            #print filenames(minus .txt suffix) with an index
  18.     while True:                
  19.         file=input("Pick a rhyme (1 to 5): ")   #pick one
  20.         if file=="q":                           #give up
  21.             sys.exit(0)
  22.         elif int(file)>=1 and int(file)<=5:     #check if valid
  23.             break
  24.         else:
  25.             print("no such rhyme, try again (or q to quit)")    #go back around
  26.  
  27.     try:
  28.         with open("rhymes//"+files[int(file)-1], 'r') as fh:    #open the correct file
  29.             content=fh.readlines()                              #read in the lines
  30.     except:
  31.         print("Error reading file")
  32.         sys.exit(0)
  33.    
  34.     print()
  35.     for lines in content:
  36.         print(lines.strip())                                    #print rhyme
  37.  
  38. #test
  39. show_rhyme()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement