首页 > 解决方案 > Strip known extension from filename

问题描述

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

标签: pythonpython-3.xtext

解决方案


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.


推荐阅读