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
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
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.