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.

+5


source to share


5 answers


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"))

      

+7


source


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

      

+2


source


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.

+2


source


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)

      

+2


source


You can use the ball

import glob
for file in glob.glob('C:\Users\UserName\Desktop\New_folder\export\*.mkv'):
    print(str(file).split('\')[-1])

      

This will list all files with the .mkv extension as file.mkv, file2.mkv

and so on.

0


source







All Articles