2

I'm basically trying to seperate file path strings into lists of files in the same path. Lets say I have this list:

files = ['user/hey.jpg','user/folder1/1.txt','user/folder1/folder2/random.txt',
         'user/folder1/blah.txt','user/folder3/folder4/folder5/1.txt',
         'user/folder3/folder4/folder5/3.txt','user/folder3/folder4/folder5/2.txt',
         'user/1.jpg']

I'm looking to get this output (not concerned about the order):

[
 ['user/folder1/1.txt','user/folder1/blah.txt']
 ['user/folder1/folder2/random.txt']
 ['user/folder3/folder4/folder5/1.txt',
  'user/folder3/folder4/folder5/2.txt','user/folder3/folder4/folder5/3.txt']
 ['user/1.jpg','user/hey.jpg']
]

Sorry if my example is sloppy. Typing on a phone is no fun. Any help is appreciated!

0

4 Answers 4

7

Use os.path.dirname as key in sorted and groupby functions should lead you to the results:

import os
from itertools import groupby
[list(g) for _, g in groupby(sorted(files, key=os.path.dirname), key=os.path.dirname)]

#[['user/hey.jpg', 'user/1.jpg'],
# ['user/folder1/1.txt', 'user/folder1/blah.txt'],
# ['user/folder1/folder2/random.txt'],
# ['user/folder3/folder4/folder5/1.txt',
#  'user/folder3/folder4/folder5/3.txt',
#  'user/folder3/folder4/folder5/2.txt']]
Sign up to request clarification or add additional context in comments.

Comments

2

Try this:

import collections
results = defaultdict(list)
for path in files:
    results[os.path.dirname(path)].append(path)

Comments

1

Another option for you, getting the set of unique directories and then using nested list comprehension.

from os.path import dirname

unique_dirs = set(dirname(s) for s in files)
output = [[f for f in files if dirname(f) == directory] 
          for directory in unique_dirs]

Comments

1

You can probably do this

>>> sorted_files = [ x for x in sorted(files, key=lambda x: x.count("/"))]
>>> max_dash = max([x.count("/") for x in sorted_files])
>>> max_dash
4
>>> newlist = [[y for y in sorted_files if y.count("/")==x] for x in range(max_dash)]
>>> newlist
[[], ['user/hey.jpg', 'user/1.jpg'], ['user/folder1/1.txt', 'user/folder1/blah.txt'], ['user/folder1/folder2/random.txt']]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.