1
votes

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

2 Answers

0
votes

You cannot pass a wildcard directly to Paramiko's SFTPClient.get.

You have to first find out the exact name and then use it with the get.

See List files on SFTP server matching wildcard in Python using Paramiko

0
votes

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