Downloading files using wildcard from SFTP server using Python Paramiko

Viewed 1812

I've a working code which works good when I mention the file name exactly how it is in folder. But these files have date and time added to its name. How can I make the file path for the same to read? Below is my code.

import paramiko
import os

paramiko.util.log_to_file('logfile.log')

host = "ftp.servername.com"
port = 22
transport = paramiko.Transport((host, port))
password = "mypass"
username = "myuser"

transport.connect(username=username, password=password)

sftp = paramiko.SFTPClient.from_transport(transport)

filepath = '/Home/user/Automation_2021-07-14_170139.csv'
localpath = 'file/dkc.csv'
sftp.get(filepath, localpath)

sftp.close()
transport.close()

How can I pass the * in the filepath? I wanted to make it like below.

filepath = '/Home/user/Automation_*.csv'
localpath = 'file/dkc.csv'
sftp.get(filepath, localpath)
2 Answers

Below code helped me to fix the issue.

latest = 0
latestfile = None

for fileattr in sftp.listdir_attr():
    if fileattr.filename.startswith('Automation_DKC') and fileattr.st_mtime > latest:
        latest = fileattr.st_mtime
        latestfile = fileattr.filename
Related