-2

I am using python to transverse into all sub folders in a directory and in order to write up the os commands. I need a list of all sub folders but the list is returning with the "./" ahead of the folder names and I am looking to remove this sub string from all list itmes simultaneously

My script so far:

import os
import glob

file_list = glob.glob("./*")
file_list.remove("./script.py")
print(file_list)

returns list

['./folder1', './folder2', './folder3', './folder4', './folder5']

I would like

['folder1', 'folder2', 'folder3', 'folder4', 'folder5']
sarahParker
  • 113
  • 4

2 Answers2

0

This can be done with a list comprehension and the str.lstrip() method.

folders = ['./folder1', './folder2', './folder3', './folder4', './folder5']

folders = [x.lstrip('./') for x in folders]

returns:

['folder1', 'folder2', 'folder3', 'folder4', 'folder5']

baileythegreen
  • 1,126
  • 3
  • 16
  • for pathname manipulations better use `os.path` or `pathlib` module – buran Apr 10 '22 at 17:12
  • 1
    @buran, in some cases, yes; but I think that really depends on what someone is trying to do. If that thing involves actually accessing those files, or needing to work with the paths, then, absolutely. If one just needs the names as text, maybe not. The question doesn't really seem to indicate something more sophisticated is a better fit here. – baileythegreen Apr 10 '22 at 17:19
0

I prefer using the pathlib module for this kind of stuff. For example, if you want to get just directory names, you can do this:

from pathlib import Path

file_list = [d.name for d in Path('.').iterdir() if d.is_dir()]
print(file_list)
flakes
  • 21,558
  • 8
  • 41
  • 88