n179911
n179911

Reputation: 20291

Build a list for all the file name of a directory

This posting shows how to add all files in a directory to an list in python

How to list all files of a directory?

onlyfiles = [ f for f in listdir(src_dir) if isfile(join(src_dir,f)) ]

How can I remove the file extension in the onlyfiles list?

Upvotes: 0

Views: 84

Answers (1)

Ffisegydd
Ffisegydd

Reputation: 53668

You can use os.path.splitext to split a filename string into the filename and the extension.

from os.path import join, splitext    

onlyfiles = [splitext(f)[0] for f in listdir(src_dir) if isfile(join(src_dir,f)) ]

Note that splitext will effectively split at the "final" extension. So if you had a filename "filename.pdf.txt" it will split it into ("filename.pdf", "txt").

Upvotes: 3

Related Questions