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?
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.
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"))
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With