how to get name of a file in directory using python

You can use glob:

from glob import glob

pth ="C:/Users/UserName/Desktop/New_folder/export/"
print(glob(pth+"*.mkv"))

path+"*.mkv" will match all the files ending with .mkv.

To just get the basenames you can use map or a list comp with iglob:

from glob import iglob

print(list(map(path.basename,iglob(pth+"*.mkv"))))


print([path.basename(f) for f in  iglob(pth+"*.mkv")])

iglob returns an iterator so you don't build a list for no reason.


os.path implements some useful functions on pathnames. But it doesn't have access to the contents of the path. For that purpose, you can use os.listdir.

The following command will give you a list of the contents of the given path:

os.listdir("C:\Users\UserName\Desktop\New_folder\export")

Now, if you just want .mkv files you can use fnmatch(This module provides support for Unix shell-style wildcards) module to get your expected file names:

import fnmatch
import os

print([f for f in os.listdir("C:\Users\UserName\Desktop\New_folder\export") if fnmatch.fnmatch(f, '*.mkv')])

Also as @Padraic Cunningham mentioned as a more pythonic way for dealing with file names you can use glob module :

map(path.basename,glob.iglob(pth+"*.mkv"))

I assume you're basically asking how to list files in a given directory. What you want is:

import os
print os.listdir("""C:\Users\UserName\Desktop\New_folder\export""")

If there's multiple files and you want the one(s) that have a .mkv end you could do:

import os
files = os.listdir("""C:\Users\UserName\Desktop\New_folder\export""")
mkv_files = [_ for _ in files if _[-4:] == ".mkv"]
print mkv_files