Aniiya0978
Aniiya0978

Reputation: 284

Sorting files from multiple directories in Python

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)

Upvotes: 0

Views: 301

Answers (1)

user2668284
user2668284

Reputation:

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

Upvotes: 1

Related Questions