Search code examples
pythonglob

Getting file names without file extensions with glob


I'm searching for .txt files only

from glob import glob
result = glob('*.txt')

>> result
['text1.txt','text2.txt','text3.txt']

but I'd like result without the file extensions

>> result
['text1','text2','text3']

Is there a regex pattern that I can use with glob to exclude the file extensions from the output, or do I have to use a list comprehension on result?


Solution

  • There is no way to do that with glob(), You need to take the list given and then create a new one to store the values without the extension:

    import os
    from glob import glob
    
    [os.path.splitext(val)[0] for val in glob('*.txt')]
    

    os.path.splitext(val) splits the file names into file names and extensions. The [0] just returns the filenames.