3

I am connecting to an SFTP folder with a list of files. I need to order these by date and extract the latest two.

filepath= "/test/sftp/files/"
localpath= "C:/myfiles/"

os.get(filepath, localpath)

I can extract all the files by using the os.get but I tried os.listdir but this does not order by date which I need. I looked in the os library but can't find something to order by date.

I'm using Paramiko.

Martin Prikryl
  • 188,800
  • 56
  • 490
  • 992
Seán Dempsey
  • 105
  • 3
  • 10

2 Answers2

6

In addition to listdir which only give the name of the remote files, paramiko provides a listdir_attr method which return a list of SFTPAttributes containing the filename and also a st_mtime field (among others). You have just to sort that list on that st_mtime field to get the list of files ordered by their (modification) date:

client = paramiko.client.SSHClient()
client.connect(...)                       # use your connection parameters here
sftp = client.open_sftp()
remote_files = [x.filename for x in sorted(sftp.listdir_attr(), key = lambda f: f.st_mtime)]
Serge Ballesta
  • 143,923
  • 11
  • 122
  • 252
-2
class MyClass1
      {
          public string DataTime { get; set; }
          public string DataTimeUTC { get; set; }
          public string Path { get; set; }  
    }
  
  SftpClient client = new SftpClient(con);
                  client.Connect();
                  var files = client.ListDirectory("");

    foreach (var file in files)
                 {
  newData.AddRange(new List<MyClass1>() {
  new MyClass1() { Path =  file.Name, DataTime = $"{file.LastWriteTime}", DataTimeUTC =  $"{file.LastWriteTimeUtc.Ticks}" } });
  }

  newData.Sort((a, b) => a.DataTimeUTC.CompareTo(b.DataTimeUTC));
Nova Ro
  • 1
  • 1