How to get the name of a file in a directory using python
In a folder named " export
" there is a mkv file. I want to make a python script that extracts the filename from this export folder. Let's say the folder is at " C:\Users\UserName\Desktop\New_folder\export
".
How do I get a name?
I tried using this os.path.basename
and os.path.splitext
.. well .. it didn't work out as I expected.
source to share
os.path
implements some useful functions for paths. But it doesn't have access to the contents of the path. For this 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 the files .mkv
, you can use fnmatch
(this module supports Unix shell-style wildcards) to get the expected filenames:
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 to handle filenames, you can use the module glob
:
map(path.basename,glob.iglob(pth+"*.mkv"))
source to share
I assume you are mainly asking how to list the files in a given directory. Do you want to:
import os
print os.listdir("""C:\Users\UserName\Desktop\New_folder\export""")
If there are multiple files and you want the ones 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
source to share
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 files ending in .mkv
.
To just get the base names, you can use a map or comp list 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 create a list for no reason.
source to share
If you are looking for recursive folder search, this method will help you get the filename using os.walk
, also you can get this path and file directory using this code below.
import os, fnmatch
for path, dirs, files in os.walk(os.path.abspath(r"C:/Users/UserName/Desktop/New_folder/export/")):
for filename in fnmatch.filter(files, "*.mkv"):
print(filename)
source to share