There is an mkv file in a folder named "export
". What I want to do is to make a python script which fetches the file name from that export folder.
Let's say the folder is at "C:\Users\UserName\Desktop\New_folder\export
".
How do I fetch the name?
I tried using this os.path.basename
and os.path.splitext
.. well.. didn't work out like I expected.
To get a filename from a path in Python, use the os. path. basename() function.
To get the filename without extension in python, we will import the os module, and then we can use the method os. path. splitext() for getting the name. After writing the above code (Python get filename without extension), Ones you will print “f_name” then the output will appear as a “ file ”.
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"))
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With