Coders Packet

Create a random music from a folder in Python

By Ramya Sri Balla

This project aims to play random music from a folder. Here we use the random module, which is an inbuilt module in Python.

In Python, there are many inbuilt functions. Here we will use the random module.

Random module

   The random module is inbuilt. It is used to generate some random data or shuffle some values. To use the random module we will need to import it and this is included in the standard library so we don't want to install it.

    there are many functions are available in random module, mainly include random(), choice().

    choice() is an inbuilt function in Python that returns a random item from the non-empty sequence.

           Syntax: random.choice(sequence) ,here sequence may be list,tuple or string.

Os module

  The os module is an inbuilt module, which allows us to access the functionality of the underlying operating system. So we can perform tasks such as navigate the file system, obtain file information, rename files, search directory trees, fetch environment variables, and many other operations.

  there are many methods available in the os module.

  os.listdir() is the most common method that enables directory and file navigation in python. Using os.listdir to read multiple files, returns a list containing the names of the entries in the directory given by the path where the mp3 files exist.

  os.startfile() method used to start any File on your PC by providing mp3 files path. 

Here we select only mp3 files from a folder by using endswith() function.

Here is the code implementation:


import os
import random 
for file in os.listdir('F:\Files'):
    if file.endswith('.mp3'):

#displays random music 
#plays an random music 


Download Complete Code


No comments yet