python - 如何在完整路径中检索文件的全名?
问题描述
我有一条这样的路径:
path = "./corpus_test/corpus_ix_test_FMC.xlsx"
我想检索没有“.xlsx”的文件名和文件的其他部分。
我知道我应该像这样使用索引,但在某些情况下文件不同,路径不同,例如:
path2 = "./corpus_ix/corpus_polarity_test_FMC.xlsx"
我正在寻找一个正则表达式或一种在两种情况下都只检索名称的方法。例如,如果我阅读完整的剧目,那里有很多文件并且使用索引对我没有帮助。有没有办法在 python 中做到这一点并告诉它应该从最后一个 "/" 开始切片?这样我只检索“/”的索引并添加“1”开始。
我尝试但仍在思考
path ="./corpus_test/corpus_ix_test_FMC.xlsx"
list_of_index =[]
for f in path:
if f == "/":
ind = path.index(f)
list_of_index.append(ind)
ind_to_start_count = max(list_of_index) + 1
print(" the index of the last "/" is" :
name_of_file = path[ind_to_start_count:-5] #
但是打印给我每个 / 1,有没有办法让字符串的字母部分的索引?
但是在这两种情况下,每个 r 的索引都是 1 吗?
想拆分字符但出错
path ="./corpus_test/corpus_ix_test_FMC.xlsx"
path_string = path.split("")
print(path_string)
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-9-b8bdc29c19b1> in <module>
1 path ="./corpus_test/corpus_ix_test_FMC.xlsx"
2
----> 3 path_string = path.split("")
4 print(path_string)
ValueError: empty separator
解决方案
import os
fullpath = r"./corpus_test/corpus_ix_test_FMC.xlsx"
full_filename = os.path.basename(fullpath)
filename, ext = os.path.splitext(full_filename)
这将为您提供不带扩展名的基本文件名
推荐阅读
- ibm-cloud - 如何在 Watson Conversation Service 中列出我的 Bot 使用的 @Cities 实体值
- c - 使用 typeof 建立单一数据类型
- javascript - JS显示属性名输入
- javascript - 如何在 JS 中正确编写此着色器函数?
- python - Plot.ly:由多个下拉菜单控制的一个图表的逻辑
- mongodb - 从每个文档的 ObjectIds 数组中获取不同的相关数据?
- numpy - 两个numpy数组的平均绝对差
- gradle - Gradle 找不到我要构建的子目录
- java - 当自定义索引不是 Firestore 中的选项时该怎么办
- node.js - 使用 express hbs 渲染时无法设置标题