I have a list of file path strings. I want to end up with a list of split file path strings.
before:
path_list = ['path/to/file.txt', 'path/to/another/file.txt', 'another/path/to/afile.txt', 'justafile.txt']
desired output:
[['path/', 'to/', 'file.txt'],
['path/', 'to/', 'another/', 'file.txt'],
['another/', 'path/', 'to/', 'afile.txt'],
['justafile.txt']]
So far I have tried the following:
path_list = ['path/to/file.txt', 'path/to/another/file.txt', 'another/path/to/afile.txt', 'justafile.txt']
new_list = []
for i in path_list:
new_list.append(Path(i).parts)
It is close, but loses the slashes (/).
>Solution :
IMO you don’t need the slashes in your path parts. And if you really do, then you could simply append os.path.sep to each part.
With that said, you can use re.split with a fixed backward looking pattern that retains the separator:
import re
import os
split_paths = [re.split(f'(?<={os.path.sep})', p) for p in path_list]
print (split_paths)
# [['path/', 'to/', 'file.txt'], ['path/', 'to/', 'another/', 'file.txt'], ['another/', 'path/', 'to/', 'afile.txt'], ['justafile.txt']]