Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Paramiko how to check if current path is directory

I’m encountering an issue while working with the paramiko library, specifically regarding the SFTPClient module. I’m attempting to recursively download files from a directory, including all subdirectories and their contents. However, I’m facing difficulty determining whether a given path is a directory or not within the SFTPClient.

I’m using the latest version of paramiko (version 3.4.0). Below is the relevant portion of my Python code:

def download_files(self, local_dir):
    if self.sftp_instance:
        current_dir = self.sftp_instance.getcwd()
        local_path = os.path.join(local_dir, os.path.basename(current_dir))
        os.makedirs(local_path, exist_ok=True)

        files = self.get_list_of_files_in_current_dir()
        for item in files:
            remote_path = os.path.join(current_dir, item)
            item_local_path = os.path.join(local_path, item)
            print("Remote path:", remote_path)
            print("cwd", self.sftp_instance.getcwd())
            print("Is directory:", self.sftp_instance.stat(item).st_isdir())  # This line raises an AttributeError
            if self.sftp_instance.stat(remote_path).isdir():  # This is where I'm experiencing issues
                if not self.sftp_instance.listdir(remote_path):
                    print(f"Skipped empty directory: {item}")
                else:
                    self.sftp_instance.chdir(remote_path)
                    self.download_files(local_path)
                    self.sftp_instance.chdir("..")
            else:
                try:
                    self.sftp_instance.get(remote_path, item_local_path)
                    print(f"Downloaded file: {item}")
                except IOError as e:
                    print(f"Error downloading file: {item}")
                    print(f"Error message: {str(e)}")
                    print(f"Error details:")
                    print(f"  errno: {e.errno}")
                    print(f"  strerror: {e.strerror}")
                    print(f"  filename: {e.filename}")
                except Exception as e:
                    print(f"Error downloading file: {item}. {str(e)}")
    else:
        print("SFTP connection not established. Please connect first.")

The specific line causing trouble is:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

print("Is directory:", self.sftp_instance.stat(item).st_isdir())

This line raises the following error:

AttributeError: 'SFTPAttributes' object has no attribute 'st_isdir'

I’ve also attempted to use the isdir() method directly on the SFTPAttributes object returned by self.sftp_instance.stat(remote_path), but it appears that this method is not available.

Is there a different approach or method provided by the paramiko library that I should be using to determine whether a given path is a directory? Any insights or alternatives would be greatly appreciated. Thank you.

>Solution :

For the stat() function call, return value is an object whose attributes correspond to the attributes of Python’s stat structure as returned by os.stat.

You can use the stat.S_ISDIR function to decide to whether the mode(st_mode) is a directory or not.

import stat
print("Is directory:", stat.S_ISDIR(self.sftp_instance.stat(item).st_mode))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading