【问题标题】:How to download folder by checking item inside it from remote server to local dir using Python?如何通过使用 Python 检查文件夹中的项目从远程服务器到本地目录来下载文件夹?
【发布时间】:2021-06-27 13:36:46
【问题描述】:

在我的根文件夹中,我有几个文件夹。 例如:

root
  AAA
    a.txt
    a.xml
  BBB
   b.txt
   b.xml
  CCC
   c.xml
  DDD
   ......

我需要下载除 DDD 之外的所有包含 .txt 文件的文件夹。 例如AAA,BBB有.txt文件,所以我需要下载它除了CCC(因为CCC不包含.txt)

我使用以下代码下载了除 DDD 之外的所有文件,但无法检查它是否包含 .txt

我试过的代码:


from paramiko import SSHClient
import paramiko
from stat import S_ISDIR

ssh = SSHClient()
ssh.load_system_host_keys()
ssh.connect('host', username='test', password='123')


remote_dir ='/root'
local_path = 'C:/download/'

def download_dir(remote_dir, local_dir):
    import os
    os.path.exists(local_dir) or os.makedirs(local_dir)
    dir_items = sftp.listdir_attr(remote_dir)
    for item in dir_items:
        # assuming the local system is Windows and the remote system is Linux
        # os.path.join won't help here, so construct remote_path manually
        if(item.filename != "DDD"):
            remote_path = remote_dir + '/' + item.filename      
            local_path = os.path.join(local_dir, item.filename)
            
                    
                    if S_ISDIR(item.st_mode):
                        download_dir(remote_path, local_path)
                
                    else:
                
                        sftp.get(remote_path, local_path)
 

download_dir(remote_dir,local_path)

我如何检查其中的文件并根据它下载文件夹?

【问题讨论】:

    标签: python python-3.x ssh sftp paramiko


    【解决方案1】:

    您可以使用 glob.glob(pathname, "*.txt") 获取目录中的所有 txt 文件。

    文档可以在here找到

    【讨论】:

    • 但我也需要复制文件夹。
    【解决方案2】:

    类似这样的:

    import fnmatch
    
    if S_ISDIR(item.st_mode):
        if any(fnmatch.fnmatch(f, "*.txt") for f in sftp.listdir(remote_path)):
            download_dir(remote_path, local_path)
    else:
        sftp.get(remote_path, local_path)
    

    这有点低效,因为您将列出所有子文件夹两次。但如果需要,您可以轻松优化它。

    基于List files on SFTP server matching wildcard in Python using Paramiko

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-30
      • 2021-10-17
      • 2014-06-09
      • 2011-01-03
      • 1970-01-01
      • 2019-03-29
      相关资源
      最近更新 更多