使用Python通过流将数据从S3传输到FTP服务器

问题描述

我想使用Python将与模式sample1相匹配的文件直接从AWS S3复制到FTP服务器,而无需下载到本地临时位置。 我尝试了以下操作:

import s3fs
from ftplib import FTP_TLS

s3 = s3fs.S3FileSystem(anon=False)
pattern = 'sample1'
rest = [i for i in list if pattern in i]
rest

ftp = FTP_TLS("ftp.test.com")
ftp.login(user ='myUser',passwd = 'PassWrd')
ftp.cwd("Box_dest")

for f in rest:
    print(f)
    with open(f,'r') as fu:
        ftp.storbinary('STOR ' + f,fu)

我得到:

[u'test-bucket/abc/test/sample1.csv']
test-bucket/abc/test/sample1.csv
Traceback (most recent call last):
  File "<stdin>",line 3,in <module>
IOError: [Errno 2] No such file or directory: u'test-bucket/abc/test/sample1.csv'

关于如何实现此目标的任何建议?谢谢!

解决方法

要从S3中读取文件,您需要使用S3FileSystem.open,而不是os.open

在指定目标FTP路径时,您只需从原始S3路径中提取文件名即可。 posixpath.basename应该做。

for f in rest:
    print(f)
    with s3.open(f,'r') as fu:
        ftp.storbinary('STOR ' + posixpath.basename(f),fu)