Specify file pattern in pysftp get
Asked Answered
G

3

13

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 ?

Generally answered 31/3, 2016 at 9:52 Comment(0)
S
11

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

You have to:


Syce answered 31/3, 2016 at 10:23 Comment(0)
K
7

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
Kola answered 11/1, 2017 at 15:26 Comment(2)
got "IndentationError: unexpected indent" on thisSomersault
@BobYoplait on which line u getting this exception? use pycharm it tells u about indentation exceptions.Flameout
S
1
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)
Somersault answered 22/1, 2018 at 16:24 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.