Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Split a list of file paths in python

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[['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']]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading