首页 > 解决方案 > 如何在完整路径中检索文件的全名?

问题描述

我有一条这样的路径:

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

标签: pythonstringsplit

解决方案


import os

fullpath = r"./corpus_test/corpus_ix_test_FMC.xlsx"
full_filename = os.path.basename(fullpath)
filename, ext = os.path.splitext(full_filename)

这将为您提供不带扩展名的基本文件名


推荐阅读