Kishore Vancheeshwaran
Listing all files and dirs with pysftp

Here is a quick snippet I wrote at work for replicating a part of tree from GNU Linux. There is more discussion here - https://stackoverflow.com/a/57694519/5675288

 1# prefix components:
 2space =  '    '
 3branch = '│   '
 4# pointers:
 5tee =    '├── '
 6last =   '└── '
 7
 8def stringpath(path):
 9    # just a helper to get string of PosixPath
10    return str(path)
11
12from pathlib import Path
13from stat import S_ISDIR
14def tree_sftp(sftp, path='.', parent='/', prefix=''):
15    """
16    Loop through files to print it out
17    for file in tree_sftp(sftp):
18        print(file)
19    """
20    fullpath = Path(parent, path)
21    strpath = stringpath(fullpath)
22
23    dirs = sftp.listdir_attr(strpath)
24    pointers = [tee] * (len(dirs) - 1) + [last]
25    pdirs = [Path(fullpath, d.filename) for d in dirs]
26    sdirs = [stringpath(path) for path in pdirs]
27
28    for pointer, sd, d in zip(pointers, sdirs, dirs):
29        yield prefix + pointer + d.filename
30        if S_ISDIR(d.st_mode):
31            extension = branch if pointer == tee else space
32            yield from tree_sftp(sftp, sd, prefix=prefix + extension)
33
34import pysftp
35with pysftp.Connection(HOSTNAME, USERNAME, PASSWORD) as sftp:
36    for file in tree(sftp):
37        print(file)
If you would like to leave a comment, contact me via email.