Python函数提取文件路径的多个段

IAm*_*aja 3 python string filepath

我想编写一个能够获取文件路径的Python函数,如:

/abs/path/to/my/file/file.txt

并返回三个字符串变量:

  • /abs - 根目录,以及路径中的"最顶层"目录
  • file - 路径中的"最底层"目录; 的父母file.txt
  • path/to/my - 路径中最顶层和最底层目录之间的所有内容

所以使用以下伪代码:

def extract_path_segments(file):
    absPath = get_abs_path(file)
    top = substring(absPath, 0, str_post(absPath, "/", FIRST))
    bottom = substring(absPath, 0, str_post(absPath, "/", LAST))
    middle = str_diff(absPath, top, bottom)

    return (top, middle, bottom)
Run Code Online (Sandbox Code Playgroud)

在此先感谢您的帮助!

Mar*_*ers 5

您正在寻找os.sep,以及各种os.path模块功能.只需按该字符拆分路径,然后重新组装要使用的部件.就像是:

import os

def extract_path_segments(path, sep=os.sep):
    path, filename = os.path.split(os.path.abspath(path))
    bottom, rest = path[1:].split(sep, 1)
    bottom = sep + bottom
    middle, top = os.path.split(rest)
    return (bottom, middle, top)
Run Code Online (Sandbox Code Playgroud)

这并不会与Windows路径,其中两个处理得非常好\ 并且 /是合法的路径分隔符.在这种情况下,你有一封驱动器号,所以无论如何你必须要特殊情况.

输出:

>>> extract_path_segments('/abs/path/to/my/file/file.txt')
('/abs', 'path/to/my', 'file')
Run Code Online (Sandbox Code Playgroud)