如何检查远程路径是文件还是目录?

问题描述 投票:11回答:3

我正在使用SFTPClient从远程服务器下载文件。但我不知道远程路径是文件还是目录。如果远程路径是一个目录,我需要递归地处理这个目录。

这是我的代码:

def downLoadFile(sftp, remotePath, localPath):
for file in sftp.listdir(remotePath):  
    if os.path.isfile(os.path.join(remotePath, file)): # file, just get
        try:
            sftp.get(file, os.path.join(localPath, file))
        except:
            pass
    elif os.path.isdir(os.path.join(remotePath, file)): # dir, need to handle recursive
        os.mkdir(os.path.join(localPath, file))
        downLoadFile(sftp, os.path.join(remotePath, file), os.path.join(localPath, file))

if __name__ == '__main__':
    paramiko.util.log_to_file('demo_sftp.log')
    t = paramiko.Transport((hostname, port))
    t.connect(username=username, password=password)
    sftp = paramiko.SFTPClient.from_transport(t)

我发现问题:函数os.path.isfileos.path.isdir返回False,所以我认为这些函数不能用于remotePath。

python paramiko
3个回答
24
投票

os.path.isfile()os.path.isdir()仅适用于本地文件名。

我将使用sftp.listdir_attr()函数来加载完整的SFTPAttributes对象,并使用st_mode模块实用程序函数检查它们的stat属性:

import stat

def downLoadFile(sftp, remotePath, localPath):
    for fileattr in sftp.listdir_attr(remotePath):  
        if stat.S_ISDIR(fileattr.st_mode):
            sftp.get(fileattr.filename, os.path.join(localPath, fileattr.filename))

4
投票

使用模块stat

import stat

for file in sftp.listdir(remotePath):  
    if stat.S_ISREG(sftp.stat(os.path.join(remotePath, file)).st_mode): 
        try:
            sftp.get(file, os.path.join(localPath, file))
        except:
            pass

3
投票

下面要遵循的步骤来验证远程路径是FILE还是DIRECTORY:

1)创建与远程的连接

transport = paramiko.Transport((hostname,port))
transport.connect(username = user, password = pass)
sftp = paramiko.SFTPClient.from_transport(transport)

2)假设你有目录“/ root / testing /”,你想通过你的代码检查。导入stat包

import stat

3)使用以下逻辑来检查其文件或目录

fileattr = sftp.lstat('root/testing')
if stat.S_ISDIR(fileattr.st_mode):
    print 'is Directory'
if stat.S_ISREG(fileattr.st_mode):
    print 'is File' 
© www.soinside.com 2019 - 2024. All rights reserved.