我想编写一个Python函数,能够接受文件路径,例如:
/abs/path/to/my/file/file.txt
并返回三个字符串变量:
- /abs - 根目录和路径中最上层的目录 - file - 路径中最下层的目录;file.txt的父级目录 - path/to/my - 路径中最上层和最下层目录之间的所有内容
伪代码如下:
/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)
提前感谢您的任何帮助!
"\"
或"/"
作为路径分隔符吗?我认为在这种情况下这不会起作用...(尽管我愿意不在Windows上工作;-) - mgilsonos.sep
总是\\
。这很痛苦,所以我定义了一个关键字参数sep
,默认为os.sep
。 - Martijn Pietersos.sep
docs 的话:“请注意,仅知道这一点是不足以解析或连接路径名的 - 请使用 os.path.split() 和 os.path.join() - 但偶尔会有用处。” - Lauritz V. Thaulow