I have a list of files that look like this:
Input
/foo/bar/baz/d4dc7c496100e8ce0166e84699b4e267fe652faeb070db18c76669d1c6f69f92.mp4
/foo/baz/bar/60d24a24f19a6b6c1c4734e0f288720c9ce429bc41c2620d32e01e934bfcd344.mp4
/bar/baz/foo/cd53fe086717a9f6fecb1d0567f6d76e93c48d7790c55e83e83dd1c43251e40e.mp4
And I would like to split out the filenames from the path while retaining both.
Output
['/foo/bar/baz/', 'd4dc7c496100e8ce0166e84699b4e267fe652faeb070db18c76669d1c6f69f92.mp4']
['/foo/baz/bar/', '60d24a24f19a6b6c1c4734e0f288720c9ce429bc41c2620d32e01e934bfcd344.mp4']
['/bar/baz/foo', 'd53fe086717a9f6fecb1d0567f6d76e93c48d7790c55e83e83dd1c43251e40e.mp4']
How would one go开发者_JS百科 about this?
Thanks!
os.path.split does exactly what you require, and I quote...:
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).
So, given a list (named e.g. paths
) of complete paths,
split_paths = [os.path.split(p) for p in paths]
should be exactly the list-of-tuples you desire. If there's any actual reason that make you request a list-of-lists instead of the natural list-of-tuples, that's not hard to make:
split_paths_as_lists = [list(os.path.split(p)) for p in paths]
精彩评论