How to list all the folders and files in the direc

2019-01-18 23:50发布

问题:

Hi i am using python and trying to connect to sftp and want to retrieve a xml file from there and need to place in my local system, below is the code

import paramiko

sftpURL   =  'sftp.somewebsite.com'
sftpUser  =  'user_name'
sftpPass  =  'password'

ssh = paramiko.SSHClient()
# automatically add keys without requiring human intervention
ssh.set_missing_host_key_policy( paramiko.AutoAddPolicy() )

ssh.connect(sftpURL, username=sftpUser, password=sftpPass)

ftp = ssh.open_sftp()
files = ftp.listdir()
print files

here connection is success full and now i want to see all the folders and all the files and need to enter in to required folder for retrieving xml file from there.

Finally my intention is to view all the folders and files after connecting to sftp server. In the above code i had used ftp.listdir() through which i got output as some thing like below

['.bash_logout', '.bash_profile', '.bashrc', '.mozilla', 'testfile_248.xml']

I want to know whether these are the only files present ?

And the command i used above is right to view the folders too ?

What is the command to view all the folders and files

回答1:

One quick solution is to examine the output of lstat of each object in ftp.listdir().

Here is how you can list all the directories.

>>> for i in ftp.listdir():
...     lstatout=str(ftp.lstat(i)).split()[0]
...     if 'd' in lstatout: print i, 'is a directory'
... 

Files are the opposite search:

>>> for i in ftp.listdir():
...     lstatout=str(ftp.lstat(i)).split()[0]
...     if 'd' not in lstatout: print i, 'is a file'
...