3

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?

Veejay
  • 515
  • 3
  • 7
  • 20

2 Answers2

9

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.

Neil
  • 14,063
  • 3
  • 30
  • 51
1

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"))
kkj
  • 50
  • 5