python - 如何使用 python 从路径中拆分文件名?

标签 python regex

我有一个看起来像这样的文件列表:

输入

/foo/bar/baz/d4dc7c496100e8ce0166e84699b4e267fe652faeb070db18c76669d1c6f69f92.mp4
/foo/baz/bar/60d24a24f19a6b6c1c4734e0f288720c9ce429bc41c2620d32e01e934bfcd344.mp4
/bar/baz/foo/cd53fe086717a9f6fecb1d0567f6d76e93c48d7790c55e83e83dd1c43251e40e.mp4

我想从路径中分离出文件名,同时保留两者。

输出

['/foo/bar/baz/', 'd4dc7c496100e8ce0166e84699b4e267fe652faeb070db18c76669d1c6f69f92.mp4']
['/foo/baz/bar/', '60d24a24f19a6b6c1c4734e0f288720c9ce429bc41c2620d32e01e934bfcd344.mp4']
['/bar/baz/foo', 'd53fe086717a9f6fecb1d0567f6d76e93c48d7790c55e83e83dd1c43251e40e.mp4']

人们会怎么做呢?

谢谢!

最佳答案

os.path.split完全按照您的要求进行操作,我引用...:

os.path.split(path)

Split the pathname path into a pair, (head, tail) where tail is the last pathname component and head is everything leading up to that. The tail part will never contain a slash; if path ends in a slash, tail will be empty. If there is no slash in path, head will be empty. If path is empty, both head and tail are empty. Trailing slashes are stripped from head unless it is the root (one or more slashes only). In nearly all cases, join(head, tail) equals path (the only exception being when there were multiple slashes separating head from tail).

因此,给定一个包含完整路径的列表(例如命名为 paths),

split_paths = [os.path.split(p) for p in paths]

应该正是您想要的元组列表。如果有任何实际原因让您请求一个列表列表而不是自然的元组列表,那不难做到:

split_paths_as_lists = [list(os.path.split(p)) for p in paths]

关于python - 如何使用 python 从路径中拆分文件名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2940909/

相关文章:

python - 具有 plotly 错误 : invalid figure_or_data argument 的 Choropleth map

python - 在 GUI 中显示 DHT11 的温度 - 自动刷新?

javascript - 允许非 ASCII 字符的(类似 twitter 的)主题标签的正则表达式

javascript - 正则表达式错误 :nothing to repeat

javascript - 在 CF 的正则表达式中排除 $

python - 使python程序可执行的问题

python - 方法调用可以链接到 'set()' 内置吗? (那么为何不?)

regex - 如何为 N 参数创建 RewriteRule?

python - 使用图像扩展 Django 管理

regex - 如何使用 Perl 检查标量中是否包含已编译的正则表达式?