使用Python从SFTP服务器下载时不要下载空文件夹 [英] Do not download empty folders while downloading from SFTP server using Python

查看:97
本文介绍了使用Python从SFTP服务器下载时不要下载空文件夹的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在此站点上,我有一段代码可以用Python递归下载文件.此代码还将下载服务器上的空目录.

I got a code to download files recursively in Python on this site. This code also downloads empty directories on server also.

请帮助我修改此代码,以便它不会从服务器下载空目录.

Please help me to modify this code so that it does not download empty directories from the server.

我拥有的代码(基于来自Linux的Python pysftp get_r在Linux上运行良好,但在Windows上无法运行)

Code I have (based on Python pysftp get_r from Linux works fine on Linux but not on Windows):

import os
import pysftp
from stat import S_IMODE, S_ISDIR, S_ISREG

cnopts = pysftp.CnOpts()
cnopts.hostkeys = None    
sftp=pysftp.Connection('192.168.X.X', username='username',password='password',cnopts=cnopts)

def get_r_portable(sftp, remotedir, localdir, preserve_mtime=False):
    for entry in sftp.listdir(remotedir):
        remotepath = remotedir + "/" + entry
        localpath = os.path.join(localdir, entry)
        mode = sftp.stat(remotepath).st_mode
        if S_ISDIR(mode):
            try:
                os.mkdir(localpath,mode=777)
            except OSError:     
                pass
            get_r_portable(sftp, remotepath, localpath, preserve_mtime)
        elif S_ISREG(mode):
            sftp.get(remotepath, localpath, preserve_mtime=preserve_mtime)

remote_path=input("enter the remote_path: ")
local_path=input("enter the local_path: ")

get_r_portable(sftp, remote_path, local_path, preserve_mtime=False)

推荐答案

您可以延迟创建本地目录,直到遇到要在此处下载的文件为止.

You can delay creating a local directory, until you encounter a file you want to download there:

from stat import S_ISDIR, S_ISREG

def get_r_portable(sftp, remotedir, localdir, preserve_mtime=False):
    for entry in sftp.listdir(remotedir):
        remotepath = remotedir + "/" + entry
        localpath = os.path.join(localdir, entry)
        mode = sftp.stat(remotepath).st_mode
        if S_ISDIR(mode):
            get_r_portable(sftp, remotepath, localpath, preserve_mtime)
        elif S_ISREG(mode):
            os.makedirs(localdir, exist_ok=True)
            sftp.get(remotepath, localpath, preserve_mtime=preserve_mtime)

这篇关于使用Python从SFTP服务器下载时不要下载空文件夹的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆