4

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?

1
  • ... By slicing them. Commented Nov 15, 2017 at 23:56

2 Answers 2

10

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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

1 Comment

basename("/a/b/c.txt") returns c.txt, WITH extension.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.