gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 19:33:42 24 4
gpt4 key购买 nike

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

输入

/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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com