Specify file pattern in pysftp get

眉间皱痕 提交于 2019-12-21 03:55:09

问题


We can write a simple get like this:

import pysftp

hostname = "somehost"
user = "bob"       
password = "123456"  
filename = 'somefile.txt'

with pysftp.Connection(hostname, username=user, private_key='/home/private_key_file') as sftp:
    sftp.get(filename)

However, I want to specify a pattern in the filename, something like: '*.txt'

Any idea on how to do this using pysftp ?


回答1:


There's no function to download files matching a file mask in pysftp.

You have to:

  • list the directory, using listdir or walktree (if you need recursion)
  • iterate the list of files, filtering the files you want
  • call get individually for each.

For an inspiration, see how get_d or get_r (recursive) are implemented.

For a trivial implementation, see List files on SFTP server matching wildcard in Python using Paramiko. For a recursive example, see Python pysftp get_r from Linux works fine on Linux but not on Windows.




回答2:


Can confirm after going through the documentation that you can't list using a pattern. So i did something like this:

import pysftp
import re

server = pysftp.Connection(host=FTP_HOST,
                  username=FTP_USERNAME,
                  password=FTP_PASSWORD)
server.cwd(YOUR_FILES_PATH)
filelist = server.listdir()

for filename in filelist:
    filedate = re.search(".*\.txt$", filename)
    if filedate:
        print "FOUND FILE " + filename



回答3:


import pysftp
import sys

[...]

dn = datetime.now().strftime("%Y%m%d%H");
with pysftp.Connection(myHost, myUsername, password=myPassword) as sftp:
    myFileList = sftp.listdir("files/")
    for filename in myFileList:
        if (filename.rfind("ArrivalList_" + dn) != -1):
            sftp.get("files/" + filename, "/tmp/" + filename)


来源:https://stackoverflow.com/questions/36329931/specify-file-pattern-in-pysftp-get

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!