0

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']
MSeifert
  • 145,886
  • 38
  • 333
  • 352
hernanavella
  • 5,462
  • 8
  • 47
  • 84

2 Answers2

10

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.

MSeifert
  • 145,886
  • 38
  • 333
  • 352
4

I wrote this but I much prefer MSeifert's answer. I checked and pathlib seems available in Python 2.7 as well.

You can try something like this

import os
import glob
print([os.path.splitext(os.path.split(x)[-1])[0] for x in glob.glob("/path/to/dir/*.txt")])

It uses a list comprehension, which you can read about here.

In glob() you can add in the path to your directory of choice.

os.path.split(x)[-1] gets the file name without the path info

os.path.splitext(...)[0] is used to split the filename.extension into a tuple `(filename, extension), of which the first element is chosen to get just the filename.

Jimbo
  • 4,352
  • 3
  • 27
  • 44
  • By making use of `glob` he cannot run the program from any other location, He has to run from that specific directory. Its better to accept a path of dirrectory. – Sanket Aug 21 '17 at 12:29
  • He can do `glob("/path/to/my/dir/*.txt")`... ah I get it, he will get the paths that he doesn;t want... correcting, thank you – Jimbo Aug 21 '17 at 12:32
  • Yes he can, but unnecessary whole file path get attached for every files, because of `glob` – Sanket Aug 21 '17 at 12:34
  • Yes, there's a backport of `pathlib` in PyPI: [`pathlib2`](https://pypi.python.org/pypi/pathlib2/). But it's not part of the standard library. You probably have that package installed if it works on 2.7. – MSeifert Aug 21 '17 at 12:37
  • What do you mean with "pathlib seems available in Python 2.7 as well"? – Stefan Pochmann Aug 21 '17 at 12:39
  • MSeifert's answer says "You could use pathlib in python 3.4+". it is also available in Python 2.7, as he points out, as a backport. I took his statement to indicate it might not be something you could use if you weren't using Python 3. – Jimbo Aug 21 '17 at 12:42