在Python中使用FTP将一个完整的压缩文件夹复制到目标可以通过以下步骤实现:
完整的代码示例:
import ftplib
import os
import zipfile
def upload_folder(ftp, local_folder, remote_folder):
for item in os.listdir(local_folder):
file = os.path.join(local_folder, item)
if os.path.isfile(file):
with open(file, 'rb') as f:
ftp.storbinary('STOR ' + os.path.join(remote_folder, item), f)
elif os.path.isdir(file):
ftp.mkd(os.path.join(remote_folder, item))
ftp.cwd(os.path.join(remote_folder, item))
upload_folder(ftp, file, '')
ftp.cwd('..')
ftp = ftplib.FTP('ftp.example.com')
ftp.login('username', 'password')
local_folder = '/path/to/local/folder'
zip_file = '/path/to/zip/file.zip'
zipf = zipfile.ZipFile(zip_file, 'w', zipfile.ZIP_DEFLATED)
for root, dirs, files in os.walk(local_folder):
for file in files:
zipf.write(os.path.join(root, file), os.path.relpath(os.path.join(root, file), os.path.join(local_folder, '..')))
zipf.close()
remote_folder = '/path/to/remote/folder'
with open(zip_file, 'rb') as f:
ftp.storbinary('STOR ' + os.path.join(remote_folder, os.path.basename(zip_file)), f)
ftp.quit()
这样,你就可以使用Python中的FTP模块将完整的压缩文件夹复制到目标FTP服务器上了。请注意,这只是一个基本示例,你可能需要根据实际情况进行适当的修改和错误处理。
领取专属 10元无门槛券
手把手带您无忧上云