- I am trying to find all
.SQLfiles 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
Trenton McKinney
63.2k41 gold badges170 silver badges214 bronze badges
-
1Share your code so others can replicate and modify for youMrinal Roy– Mrinal Roy2020年07月15日 19:13:55 +00:00Commented Jul 15, 2020 at 19:13
2 Answers 2
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]
answered Jul 15, 2020 at 19:13
Red
27.7k8 gold badges44 silver badges63 bronze badges
Sign up to request clarification or add additional context in comments.
2 Comments
shubham garg
Many Thanks Ann, I was looking for something similar.. is it possible to make this more dynamic.. example- c/few folders/folder 1/folder 2/file.sql and I get output folder 1/folder 2/file.sql
Red
@shubhamgarg Updated.
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].
answered Jul 15, 2020 at 19:30
wjakobw
5331 gold badge4 silver badges11 bronze badges
1 Comment
shubham garg
Thanks mate .. I will try this
lang-py