Storing the name of several folders in a variable list

Viewed 47

I have 47 folders (100, 00, 01, 02, ..., 43, 44, 45). I want to store the name of these folders inside a list so that I can build a pandas Dataframe with it. So far, I have this code:

import os
import glob
path = '/content/drive/MyDrive/data/classes/'
ListOfClasses = []
for file in glob.glob (path + '/*'):
    ListOfClasses.append(file)
ListOfClasses

However, the names of the folders come out like this (They also come unorganized):

['/content/drive/MyDrive/data/classes/42',
 '/content/drive/MyDrive/data/classes/43',
 '/content/drive/MyDrive/data/classes/36',
 '/content/drive/MyDrive/data/classes/45',
 ...,
 '/content/drive/MyDrive/data/classes/00',
 '/content/drive/MyDrive/data/classes/02',
 '/content/drive/MyDrive/data/classes/04']

How can I transform the previous way into this:

['00',
 '01',
 '02',
 '03',
 ...,
 '44',
 '45',
 '100']
3 Answers

Instead of using the glob module, I would use the pathlib module. pathlib.Path.glob yields a collection of pathlib.Path objects, rather than strings. Since they are path-objects, you can select only each path's stem to cull all the stuff that comes before. Then, you can sort the stem-strings as if they were integers:

from pathlib import Path

path = "/content/drive/MyDrive/data/classes/"

list_of_classes = sorted([p.stem for p in Path(path).glob("*")], key=int)

You can split the strings on /. rsplit('/', 1) will split on the first / from the right, rsplit('/', 1)[1] will give you the folder name:

ListOfClasses = ['/content/drive/MyDrive/data/classes/42','/content/drive/MyDrive/data/classes/43','/content/drive/MyDrive/data/classes/36','/content/drive/MyDrive/data/classes/45']
[i.rsplit('/', 1)[1] for i in ListOfClasses]

Result:

['42', '43', '36', '45']

You do not need glob or pathlib.

import os

list_of_classes = os.listdir('/content/drive/MyDrive/data/classes')
Related