-1

I want to use python to check if any mp3 files exist in a specified directory. If it does exist, I want to store the file path in a variable.

Here is some code I have to check if any file exists. How can I modify it?

import os
dir = os.path.dirname(__file__) or '.'
dir_path = os.path.join(dir, '../folder/')
onlyfiles = [f for f in os.listdir(dir_path) if os.path.isfile(os.path.join(dir_path, f))]
Juliette
  • 4,309
  • 2
  • 14
  • 31
  • "How can I modify it" is not a helpful question. What are you trying to accomplish, what have you tried, and how is it not working? You got the first part, now answer the second and third! – smp55 Jun 25 '21 at 15:29
  • Does this answer your question? [Find a file in python](https://stackoverflow.com/questions/1724693/find-a-file-in-python) – mpx Jun 25 '21 at 15:45

3 Answers3

1

Simply add the additional condition f[-4:]==".mp3" to the if statement within your list comprehension such that it now reads:

onlyfiles = [f for f in os.listdir(dir_path) if os.path.isfile(os.path.join(dir_path, f)) and f[-4:]==".mp3"]
Georgy Kopshteyn
  • 678
  • 3
  • 13
0

Try this:

import os

dir = os.path.dirname("/path/to/your/dir/"); dir_path = dir;
onlyfiles = [f for f in os.listdir(dir_path) if os.path.isfile(os.path.join(dir_path, f)) and f[-4:]==".mp3"]
kiner_shah
  • 3,939
  • 7
  • 23
  • 37
0

I personally like the pathlib module better so I'm going to post an answer using it. Keep in mind though that this isn't a recursive approach so it's only going to go one level down and search for the .mp3 files you want:

import pathlib as path

dirname = path.Path(input("Enter the path to the directory to search: ")).glob("*.mp3")
paths = []

for file in dirname:
    paths.append(str(file))

I stored the paths in a list instead just in case there were more .mp3 files in the folder.

Matthew Schell
  • 599
  • 1
  • 6
  • 19