从完整文件路径中提取文件名及其父目录的 Pythonic 方法?

Pythonic way to extract the file name and its parent directory from the full file path?

我们有文件的完整路径:

/dir1/dir2/dir3/sample_file.tgz

基本上,我想以这个字符串结束:

dir3/sample_file.tgz

我们可以用 regex.split("/") 解决它,然后将列表中的最后两项连接起来.....但我想知道我们是否可以做得更时尚使用 os.path.dirname() 或类似的东西?

import os
full_filename = "/path/to/file.txt"
fname = os.path.basename(full_filename)
onedir = os.path.join(os.path.basename(os.path.dirname(full_filename)), os.path.basename(full_filename))

没有人说过 os.path 很好用,但无论平台如何,它都应该做正确的事情。

如果您在 python3.4(或更高,大概),则有 pathlib:

import os
import pathlib
p = pathlib.Path("/foo/bar/baz/txt")
onedir = os.path.join(*p.parts[-2:])