0

I am trying to read and store the file names from a directory to a list.

The folder structure is:

dataset
  ├── Type_a
  │   ├── a1_L.wav
  │   ├── a1_R.wav
  │   ├── a2_L.wav
  │   └── a2_R.wav
  └── Type_b
      ├── a1_L.wav
      ├── a1_R.wav
      ├── a2_L.wav
      └── a2_R.wav

The expected list output should be:

[[a1_L.wav,a1_R.wav],[a2_L.wav,a2_R.wav],[a1_L.wav,a2_R.wav],[a2_L.wav,a2_R.wav]]

Using the following code i am getting the file names but how it can be grouped into a list

import os
    for i, ret in enumerate(os.walk('./dataset/')):
        for i, filename in enumerate(ret[2]):
            print("filename is",filename)
7
  • The order of the filenames in a directory is hard is even possible to predict. What gives the order in your example? Commented Sep 16, 2021 at 12:48
  • It was created in this manner.. I cant say why its so :( Commented Sep 16, 2021 at 12:52
  • So.. sorted by creation date? Or file name? Commented Sep 16, 2021 at 13:02
  • @Axe319 By filename Commented Sep 16, 2021 at 13:04
  • Not quite sure what's the expected output.. a list of lists (of size 2) with the files that start with the same string? But you have a1_L.wav alongside a2_R.wav, which would break this rule. So what is the goal here? Commented Sep 16, 2021 at 13:22

1 Answer 1

1

You could do it like this:-

import glob
import os

D={}

for r in glob.glob('./dataset/Type_*/*.wav'):
    t = r.split(os.path.sep)
    if not t[-2] in D:
        D[t[-2]] = []
    D[t[-2]].append(t[-1])
out = []
for v in D.values():
    v.sort()
    for i in range(0,len(v),2):
        out.append([v[i], v[i+1]])
print(out)

WARNING: This will fail if there are an odd number of files in any of the Type_* directories

Sign up to request clarification or add additional context in comments.

2 Comments

@DarkKnight This will fail for more entries
Thank you @Axe319 - I have corrected my answer

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.