Finding folder & subfolder in python

Viewed 79
  • I am trying to find all .SQL files from my folder and it's sub folders.
  • I know how to get them, but I get output like
c/folder1/folder2/file.sql
  • I want output like
folder1/folder2/file.sql
2 Answers

You can use the str.split():

s = 'c/folder1/folder2/file.sql'
s = '/'.join(s.split('/')[1:])

print(s)

Output:

folder1/folder2/file.sql

UPDATE: More dynamic:

s = 'c/few folders/folder 1/folder 2/file.sql and I get output folder 1/folder 2/file.sql'
s = 'folder 1' + s.split('folder 1')[1]

You might want to use pathlib from the standard library, in particular pathlib.Path and the glob method, like this:

import pathlib
parent = pathlib.Path(path_to_parent_directory)
sql_paths = sorted(parent.glob("**/*.SQL"))

To get the relative paths and the strings:

relative_paths = [p.relative_to(parent) for p in sql_paths]

You can keep working with these path objects, or you can convert them to strings with the as_posix method: [p.as_posix() for p in relative_paths].

Related