Demo entry 6719596

OCRTUNES

   

Submitted by anonymous on Mar 12, 2018 at 12:34
Language: Python 3. Code size: 7.6 kB.

import pickle #To save the file as binary
import glob #To find all files with extension in directory
import getpass #Asterix passwrd input
import datetime #to validate date inputs
from operator import itemgetter#To order a 2D list

global songs

songs = [
["Slippery", "Migos", "Hip Hop", 5.2], 
["Song2", "Artist1", "Rap", 1], 
["Song3", "Artist1", "Rap", 1], 
["Song4", "Artist1", "Rap", 1], 
["Song5", "Artist1", "Rap", 1], 
["Song6", "Artist1", "Rap", 1], 
["Song7", "Artist1", "Rock", 1], 
["Song8", "Artist1", "Rock", 1], 
["Song9", "Artist1", "Rock", 1], 
["Song10", "Artist1", "Rock", 1], 
["Song11", "Artist1", "Rock", 1], 
["Song12", "Artist1", "Rock", 1], 
["Song13", "Artist1", "Rock", 1], 
["Song14", "Artist1", "Pop", 1], 
["Song15", "Artist1", "Pop", 1], 
["Song16", "Artist1", "Pop", 1], 
["Song17", "Artist1", "Pop", 1], 
["Song18", "Artist1", "Pop", 1], 
["Closer", "The Chainsmokers", "Pop", 4], 
["Paris", "The Chainsmokers", "Pop", 3.6], 
["Counting Stars", "One Republic", "Pop", 4.6], 
]

def registerUser():
        print("#Registering User#")
        name = input("Name: ")
        password = input("Password: ")
        validDOB = False
        #while validDOB
        dob = input("Date Of Birth: ")
        fArtist = input("Favourite Artist: ")
        fGenre = input("Favourite Genre: ")
        register = open("login.txt", "w")
        register.write(name + "," + password + "," + dob + "," + fArtist + "," + fGenre)
        register.close()

def loginUser():
    try:
        test = open("login.txt", "r")
        user_exists = True
        test.close()
    except Exception as e:user_exists = False

    if user_exists == True:
        print("#User Log On Page#")
        for line in open("login.txt"):
                details = line.split(",")
        username = input("Name: ")
        password = input("Password: ")
        
        if details[0] == username and details[1] == password:
            return username
        else:
            return False
    else:
        registerUser()


def editUser():
    for line in open("login.txt"):
            details = line.split(",")
    fArtist = input("Favourite Artist: ")
    fGenre = input("Favourite Genre: ")
    save = open("login.txt", "w")
    save.write(details[0] + "," + details[1] + "," + details[2] + "," + fArtist + "," + fGenre)
    save.close()

def displaySongs(s = globals()["songs"]):
    print("\n" * 2)
    s = sorted(s, key=itemgetter(1)) #Modified code from https://stackoverflow.com/questions/18563680/sorting-2d-list-python
    print("Song name  Artist  Genre  Song Duration (minutes)")
    for song in s:print(song[0] + "  " + song[1] + "  " + song[2] + "  " + str(song[3]))
    print("\n" * 2)

def getSongsGenre(genre):
    genreSongs = []
    for song in songs:
        if song[2] == genre and len(genreSongs) < 5:
            genreSongs.append(song)
    savePlaylist(genreSongs)
    displaySongs(genreSongs)

def getSongsTime(maxtime):
    currentLength = 0
    timeSongs = []
    for song in songs:
        if int(currentLength + int(song[3])) <= 10:
            timeSongs.append(song)
            currentLength += int(song[3])
    savePlaylist(timeSongs)
    displaySongs(timeSongs)

def saveArtistSongs():
    artistSongs = []
    artist = input("Artist: ")
    for song in songs:
        if song[1] == artist:artistSongs.append(song)

    saveSongs = open(artist +"Songs.txt", "w")
    saveSongs.write(song[0] + "," + song[1] + "," + song[2] + "," + str(song[3]))
    saveSongs.close()

def savePlaylist(playListsongs):
    filename = input("Playlist name: ")
    filename = filename + ".binary"
    if filename in glob.glob("*.binary"):
            print("Playlist Already Exists!")
            overwrite = ""
            while overwrite.lower() not in ("yes", "no"):
                    overwrite = input("Do you wish to overwrite the playlist? ")
            if overwrite == "no":return
            else:print("File Overwritten! ")

        ###open binary file, write mode, and save the array playListSongs to it.
    pickle.dump(playListsongs, open(filename, "wb"))

def viewPlaylist():
    listSavedPlaylists()
    filename = input("Playlist To View: ")
    filename = filename + ".binary"
    playlist = pickle.load(open(filename, "rb")) ###open binary file, read mode - save data as the array playlist
    displaySongs(playlist)

def listSavedPlaylists():
        print("Saved Playlists:")
        playlistNames = glob.glob("*.binary") #Get all .binary files in current directory, modified code from https://stackoverflow.com/questions/3964681/find-all-files-in-a-directory-with-extension-txt-in-python
        for pName in playlistNames:
                print(pName.replace(".binary", ""))
        print("\n")
        
def customPlaylist():
        songNames = []
        playlist = []
        for song in songs:songNames.append(song[0])
        songAdd = ""
        while songAdd.lower() != "exit":
            songAdd = input("(Press Exit to stop adding new songs)\nSong Name to Add: ")
            if songAdd not in songNames and songAdd.lower() != "exit":
                print("That song is not in the library. If you wish to stop adding songs to the playlist, then ")
            else:
                if songAdd.lower() != "exit":
                        for song in songs:
                                if song[0] == songAdd:playlist.append(song)

                
        savePlaylist(playlist)
        displaySongs(playlist)



def menu():
        print("\n")
        choice = ""
        while choice not in ("1", "2", "3", "4", "5", "6", "7", "8"):choice = input("Menu (Pick the number):\n1 Edit Account Favourites\n2 Display Songs\n3 Create a custom playlist\n4 Generate a playlist by time\n5 Generate a playlist by genre\n6 Save all songs by artist to a file\n7 Display List of genres\n8 View a Playlist\n")
        if choice == "1":
                editUser()
        elif choice == "2":
                displaySongs()
        elif choice == "3":
                customPlaylist()
        elif choice == "4":
                time = int(input("Time in minutes for playlist: "))
                getSongsTime(time)
        elif choice == "5":
                genre = input("Genre for playlist: ")
                getSongsGenre(genre)
        elif choice == "6":
                saveArtistSongs()
        elif choice == "7":
                for genre in ("Pop", "Rap", "Rock"):
                        songCount = 0
                        totalTime = 0
                        for song in songs:
                                if song[2] == genre:
                                        songCount += 1
                                        totalTime += song[3]

                        averageTime = totalTime / songCount
                        print(genre + ":")
                        print("Song Count: " + str(songCount))
                        print("Total Time: " + str(totalTime))
                        print("Average Time: " + str(averageTime) + "\n\n")
                        
        elif choice == "8":viewPlaylist()


username = False
while username == False:
    username = loginUser()


while True:
    menu()


#Bibliography

#https://stackoverflow.com/questions/18563680/sorting-2d-list-python
#https://stackoverflow.com/questions/3964681/find-all-files-in-a-directory-with-extension-txt-in-python

This snippet took 0.02 seconds to highlight.

Back to the Entry List or Home.

Delete this entry (admin only).