I've written a function, which returns the absolute path of files after the traverse searching.

But how to return only last folder name and file name for each file (in conjunction) ?

For example, I have 3 files:

  • "D:\python\demo_project\dir1\dir2\dir3\file1.sql"

  • "D:\python\demo_project\dir1\dir2\file2.sql"

  • "D:\python\demo_project\dir1\file3.sql"

The results should be:

  • dir3\file1.sql

  • dir2\file2.sql

  • dir1\file3.sql

def find_sql(main_dir):
    arr = []
    for dirpath, subdirs, files in walk(main_dir):
        arr.extend(path.join(dirpath, x) for x in files if x.endswith(".sql"))

    return arr

call_find_sql = find_sql("D:\\python\\demo_project")

1 Answers

1
wjandrea On

Use os.path.basename on dirpath.

For example it will convert 'D:\\python\\demo_project\\dir1\\dir2\\dir3' to 'dir3'.

from os import walk, path

def find_sql(main_dir):
    arr = []
    for dirpath, subdirs, files in walk(main_dir):
        arr.extend(
            path.join(path.basename(dirpath), x)
            for x in files
            if x.endswith(".sql")
            )
    return arr