hernanavella hernanavella - 2 months ago 11
Python Question

Pythonic way to create a list of strings from file names (without file extension) in folder?

I have a folder in my computer with many

.txt
files:

file_one.txt --> location = r'C:\Users\User\data\file_one.txt'
file_two.txt --> location = r'C:\Users\User\data\file_two.txt'
file_forty.txt --> location = r'C:\Users\User\data\file_forty.txt'


How can I turn the name of the files (without the
.txt
part) into a list like this:

list_from_files = ['file_one', 'file_two', 'file_forty']

Answer Source

You could use pathlib1. It has a dedicated stem property which returns the filename without suffix:

import pathlib

p = pathlib.Path('.')   # current directory, insert your directory here
[x.stem for x in p.glob('*.txt')]

1 pathlib is part of the standard library in Python 3.4+ - but you can use third-party (backport-)packages, available on PyPI and conda, like pathlib and pathlib2 if you have an older Python version.