Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get name of a file in directory using python

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.

like image 489
Xonshiz Avatar asked Jul 04 '15 15:07

Xonshiz


People also ask

How do you get the name of a file from a path in Python?

To get a filename from a path in Python, use the os. path. basename() function.

How do I get the name of a file object in Python?

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 ”.


2 Answers

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"))
like image 95
Mazdak Avatar answered Sep 20 '22 19:09

Mazdak


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.

like image 25
Padraic Cunningham Avatar answered Sep 19 '22 19:09

Padraic Cunningham