簡體   English   中英

如何在完整路徑中檢索文件的全名?

[英]How to retrieve the full name of a file in a full path?

我有這樣一條路徑:

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)

這將為您提供不帶擴展名的基本文件名

這是我一直在使用的:

def get_suffix(word, delimeter):
    """ Returns the part of word after the last instance of 'delimeter' """
    while delimeter in word:
        word = word.partition(delimeter)[2]
    return word


def get_terminal_path(path):
    """
    Returns the last step of a path
    Edge cases:
    -Delimeters: / or \\ or mixed
    -Ends with delimeter or not
    """
    # Convert "\\" to "/"
    while "\\" in path:
        part = path.partition("\\")
        path = part[0] + "/" + part[2]
    # Check if ends with delimeter
    if path[-1] == "/":
        path = path[0:-1]
    # Get terminal path
    out = get_suffix(path, "/")
    return out.partition(".")[0]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM