FTP(File Transfer Protocol,文件传输协议)是一种用于在网络上进行文件传输的标准协议。它允许用户在不同的计算机之间传输文件,广泛应用于网站管理、文件备份和数据共享等场景。FTP有两种主要的上传文件模式:ASCII模式和二进制模式。
from ftplib import FTP
def upload_file(host, user, passwd, local_path, remote_path, mode='binary'):
ftp = FTP(host)
ftp.login(user=user, passwd=passwd)
if mode == 'ascii':
ftp.sendcmd('TYPE A') # 设置为ASCII模式
else:
ftp.sendcmd('TYPE I') # 设置为二进制模式
with open(local_path, 'rb') as file:
ftp.storbinary(f'STOR {remote_path}', file)
ftp.quit()
# 使用示例
upload_file('ftp.example.com', 'username', 'password', 'local_file.txt', 'remote_file.txt', mode='ascii')
upload_file('ftp.example.com', 'username', 'password', 'local_image.jpg', 'remote_image.jpg', mode='binary')
通过以上代码,可以根据文件类型选择合适的传输模式进行FTP上传操作。
总之,正确选择FTP的上传模式对于确保文件传输的正确性和完整性至关重要。
领取专属 10元无门槛券
手把手带您无忧上云