How to get a list of filenames(without extension) in directory in python?

Question:

Assume my folder structure to be

+Data
  -abc.jpg
  -db.jpg
  -ap.jpg

Input is ‘path/to/Data’

Expected output is [‘abc’,’db’,’ap’]

I saw many similar questions but did not get what exactly I wanted.
I prefer to use os module in python.

Asked By: Sreeragh A R

||

Answers:

import os    
files_no_ext = [".".join(f.split(".")[:-1]) for f in os.listdir() if os.path.isfile(f)]
print(files_no_ext)
Answered By: Keatinge

You can use os.listdir which take path as argument and return a list of files and directories in it.
>>> list_ = os.listdir("path/to/Data")
>>> list_
>>> ['abc.jpg', 'dn.jpg', 'ap.jpg']

With that list, you only have to do a comprehension list which split each element on ‘.’ (dot), take all the elements except the last one an join them with ‘.’ (dot) and check if the element is a file using os.path.file().

>>> list_ = ['.'.join(x.split('.')[:-1]) for x in os.listdir("path/to/Data") if os.path.isfile(os.path.join('path/to/Data', x))]
>>> list_
>>> ['abc', 'dn', 'ap']

Answered By: Darkaird
    import os
    from os import listdir
    from os.path import isfile, join
    def filesMinusExtension(path):
        # os.path.splitext(f)[0] map with filename without extension with checking if file exists.
        files = [os.path.splitext(f)[0] for f in listdir(path) if isfile(join(path, f))];
        return files;
Answered By: grimur82

simply try this,

l=os.listdir('path')
li=[x.split('.')[0] for x in l]
  1. First list your directory files
  2. split file by. and take first argument.
Answered By: Mohamed Thasin ah
import os
filenames=next(os.walk(os.getcwd()))[2]
efn=[f.split('.')[0] for f in filenames]

os.getcwd()   #for get current directory path
Answered By: Ahmad
import glob
from pathlib import Path

for f in glob.glob("*.*"):
    print(Path(f).stem)
Answered By: LetzerWille
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.