0

I have a bunch of txt files. I want to strip out the .txt from the filename (which I am reading via os.walk).

How could I achieve this?

fileName.rstrip(".txt") seems to remove the letters .,t,x rather than removing the substring .txt

OC2PS
  • 1,037
  • 3
  • 19
  • 34

2 Answers2

1

I would recomment using the OS library.

name, ext = os.path.splitext(path)
azb_
  • 387
  • 2
  • 10
0

I would use rpartition (partition from right), and get the first elemnet from resulting tuple:

fileName.rpartition(".txt")[0]

rpartition is guaranteed to generate a 3-element tuple in the form:

(before, sep, after)

So, for filenames with .txt extension e.g. foobar.txt you would get:

('foobar', '.txt', '')

For files that does not end with .txt e.g. foobar:

('foobar', '', '')

so getting the first element would work in all cases.

heemayl
  • 39,294
  • 7
  • 70
  • 76