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
  • 955
  • 3
  • 18
  • 31

2 Answers2

1

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
  • 35,775
  • 6
  • 62
  • 69
1

I would recomment using the OS library.

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