将一个 SFTP 文件夹中的所有文件存档到 Python 中的另一个文件夹
Archive all files from one SFTP folder to another in Python
我能够使用@Martin Prikryl .
给出的以下语法成功地将文件从 S3 上传到 SFTP 位置
with sftp.open('/sftp/path/filename', 'wb') as f:
s3.download_fileobj('mybucket', 'mykey', f)
我需要在将当前日期的文件从 S3 上传到 SFTP 之前将之前的文件从当前文件夹存档到 archive
文件夹
我正在尝试使用通配符来实现,因为有时,当 运行 星期一时,您将无法找到星期日的文件,而您有上一个文件,即星期五的文件。所以我想实现任何以前的文件,不管日期如何。
例子
我有如下文件夹,filename_20200623.csv
需要移动到 ARCHIVE
文件夹,新文件 filename_20200625.csv
将被上传。
MKT
ABC
ARCHIVE
filename_20200623.csv
预计
MKT
ABC
ARCHIVE
filename_20200623.csv
filename_20200625.csv
使用Connection.listdir_attr
to retrieve list of all files in the directory, filter it to those you are interested in, and then using Connection.rename
:
remote_path = "/remote/path"
archive_path = "/archive/path"
for f in sftp.listdir_attr(remote_path):
if (not stat.S_ISDIR(f.st_mode)) and f.filename.startswith('prefix'):
remote_file_path = remote_path + "/" + f.filename
archive_file_path = archive_path + "/" + f.filename
print("Archiving %s to %s" % (remote_file_path, archive_file_path))
sftp.rename(remote_file_path, archive_file_path)
对于使用 Paramiko 的未来读者,代码将是相同的,当然 sftp
将引用 Paramiko SFTPClient
class, instead of pysftp Connection
class. As Paramiko SFTPClient.listdir_attr
and SFTPClient.rename
方法,其行为与 pysftp 的方法相同。
我能够使用@Martin Prikryl
with sftp.open('/sftp/path/filename', 'wb') as f:
s3.download_fileobj('mybucket', 'mykey', f)
我需要在将当前日期的文件从 S3 上传到 SFTP 之前将之前的文件从当前文件夹存档到 archive
文件夹
我正在尝试使用通配符来实现,因为有时,当 运行 星期一时,您将无法找到星期日的文件,而您有上一个文件,即星期五的文件。所以我想实现任何以前的文件,不管日期如何。
例子
我有如下文件夹,filename_20200623.csv
需要移动到 ARCHIVE
文件夹,新文件 filename_20200625.csv
将被上传。
MKT
ABC
ARCHIVE
filename_20200623.csv
预计
MKT
ABC
ARCHIVE
filename_20200623.csv
filename_20200625.csv
使用Connection.listdir_attr
to retrieve list of all files in the directory, filter it to those you are interested in, and then Connection.rename
:
remote_path = "/remote/path"
archive_path = "/archive/path"
for f in sftp.listdir_attr(remote_path):
if (not stat.S_ISDIR(f.st_mode)) and f.filename.startswith('prefix'):
remote_file_path = remote_path + "/" + f.filename
archive_file_path = archive_path + "/" + f.filename
print("Archiving %s to %s" % (remote_file_path, archive_file_path))
sftp.rename(remote_file_path, archive_file_path)
对于使用 Paramiko 的未来读者,代码将是相同的,当然 sftp
将引用 Paramiko SFTPClient
class, instead of pysftp Connection
class. As Paramiko SFTPClient.listdir_attr
and SFTPClient.rename
方法,其行为与 pysftp 的方法相同。