Hrittik Chatterjee
Hrittik Chatterjee

Reputation: 68

How to make python count how many files are in a directory?

Just by the title, you might think that this is a duplicate but it is not. I need to make my program count how many files with a specific ending such as .mp3 or .mp4 are in a directory. So if I have 10 .mp3 files in a directory I want my program to figure that out. After that, I need to list those files with numbers next to them so that the user can enter a number to launch that file. I need help with counting the files.

Upvotes: 0

Views: 4344

Answers (1)

wishmaster
wishmaster

Reputation: 1487

import os 
i=0
x=[]
for file in os.listdir():
    if file.endswith('.mp3'):
        print(file)
        x.append(file)
        i+=1
print('the total number of files: ' +str(i))
fileNumber=input('enter number')
os.startfile(x[int(fileNumber)])

make sure to use change directory to the folder location using os.chdir() or enter complete path in os.listdir()

Upvotes: 2

Related Questions