Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get filenames in a directory without extension - Python [duplicate]

Tags:

python

I am trying to get the filenames in a directory without getting the extension. With my current code -

import os

path = '/Users/vivek/Desktop/buffer/xmlTest/' 
files = os.listdir(path) 
print (files)

I end up with an output like so:

['img_8111.jpg', 'img_8120.jpg', 'img_8127.jpg', 'img_8128.jpg', 'img_8129.jpg', 'img_8130.jpg']

However I want the output to look more like so:

['img_8111', 'img_8120', 'img_8127', 'img_8128', 'img_8129', 'img_8130']

How can I make this happen?

like image 847
Veejay Avatar asked Oct 31 '25 14:10

Veejay


2 Answers

You can use os's splitext.

import os

path = '/Users/vivek/Desktop/buffer/xmlTest/' 
files = [os.path.splitext(filename)[0] for filename in os.listdir(path)]
print (files)

Just a heads up: basename won't work for this. basename doesn't remove the extension.

like image 164
Neil Avatar answered Nov 03 '25 06:11

Neil


Here are two options

import os
print(os.path.splitext("path_to_file")[0])

Or

from os.path import basename
print(basename("/a/b/c.txt"))
like image 35
kkj Avatar answered Nov 03 '25 07:11

kkj