python - 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
解决方案
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.
推荐阅读
- javascript - 试图弄清楚为什么代码不会呈现列表
- tensorflow - 调用 tf.keras.model.fit 时,Tensorflow 2.0 不会遍历整个数据集
- java - Mockito.mock 何时创建部分模拟而不是“完整”模拟?
- r - 将 DT::datatable 从闪亮转换为 Rmarkdown PDF
- markdown - 为什么有些静态站点生成器使用 README.md 而不是 index.md?
- c++ - 在 C++ 中使用带有自定义向量的迭代器
- javascript - JavaScript 代码原因
和 - python-3.x - Scrapy:无法在初始化中创建具有 *arg 和 **kwarg 的类的对象
- python - 与子流程的相对导入
- spring-batch - Spring Batch 创建子作业