Order SFTP files by date
Question:
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.
Answers:
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)]
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));
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.
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)]
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));