How to list all the folders and files in the directory after connecting through SFTP in Python

前端 未结 2 1156
自闭症患者
自闭症患者 2020-12-05 11:00

I am using Python and trying to connect to SFTP and want to retrieve an XML file from there and need to place it in my local system. Below is the code:

impor         


        
2条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-05 11:14

    The SFTPClient.listdir returns everything, files and folders.

    Were there folders, to tell them from the files, use SFTPClient.listdir_attr instead. It returns a collection of SFTPAttributes.

    from stat import S_ISDIR, S_ISREG
    
    for entry in sftp.listdir_attr(remotedir):
        mode = entry.st_mode
        if S_ISDIR(mode):
            print(entry.filename + " is folder")
        elif S_ISREG(mode):
            print(entry.filename + " is file")
    

    The accepted answer by @Oz123 is inefficient. SFTPClient.listdir internally calls SFTPClient.listdir_attr and throws most information away returning file and folder names only. The answer then uselessly and laboriously re-retrieves all that data by calling SFTPClient.lstat for each file.

    See also How to fetch sizes of all SFTP files in a directory through Paramiko.


    Obligatory warning: Do not use AutoAddPolicy – You are losing a protection against MITM attacks by doing so. For a correct solution, see Paramiko "Unknown Server".

提交回复
热议问题