Search code examples
pythonoptimization

Python Reaching File optimization


I had a question about optimization on python.

I have a code for a jukebox. This jukebox plays lists of songs (eg. list 1 plays song 1, 2, 3, list 2 plays song 4, 5, 6 etc.)

Each of these lists have a different lenght. I first thought that it was easier to read a txt file that contains the list. Here is how it should have looked.


song1.wav song2.wav song3.wav
song4.wav song5.wav son6.wav
song7.wav
song8.wav song9.wav song10.wav song11.wav

Then, with a few line, I would be able to read the lenght of lists and the file names. I then had another idea: put the list names in the file names, like shown below.

1_1.wav, 1_2.wav, ... , 2_4.wav, ...

So, I was wondering, which method was preferable. The first one seems easier to set up, but the second one seems most efficient. Am I right ? Any other opinions ?

Thanks ! :)


Solution

  • Use an array to organize the .wav files into two sections.

    JukeboxPlaylist = []
    
    # This will let you read the file
    with open('filename.txt', 'r') as file:
        wordCount = 0
        # Wav files 1-3
        sectionA = []
        # Wav files 4-...
        sectionB = []
    
        # for each line in ‘file’
        for line in file:
            # for each word in the line
            for word in line.split():
                # 'wordCount' keeps track of what word the program is on.
                wordCount = wordCount+1
                # if wordCount is less than four, it will add it to sectionA of the playlist
                if wordCount < 4:
                    sectionA.append(word)
                # if the wordCount has exceeded four, then it will add it to sectionB.
                else:
                    sectionB.append(word)
    
        # Adds both sectionA and sectionB to the final list.
        JukeboxPlaylist.append(sectionA)
        JukeboxPlaylist.append(sectionB)
    

    This code will allow you to organize the wav files however you would like and it would still give you the same list output in JukeboxPlaylist. So you could have your original

    song1.wav song2.wav song3.wav
    song4.wav song5.wav son6.wav
    song7.wav
    song8.wav song9.wav song10.wav song11.wav
    

    and get [[song1.wav, song2.wav, song3.wav], [song4.wav, ...]] or use your

    1_1.wav, 1_2.wav, ... , 2_4.wav, ...
    

    and also get [[1_1.wav, 1_2.wav, 1_3.wav], [2_4.wav, 2_5.wav, ...]]

    In order to call a specific song, you would have to do JukeboxPlaylist[x][x] with the first brackets being either sectionA (0) or sectionB (1). The second set of brackets being the index of the song. Using this, you can create a for loop or function that will increase the index by one every time it finishes a song.