我正在尝试构建一个小型 FTPClient 作为我的宠物项目,并且已经走到了这一步。
from ftplib import FTP
class FTPClient():
connection_id = None
login_ok = False
message_array = []
def __init__(self):
pass
def log_message(self, message, clear=True):
if clear:
self.message_array = message
def get_message(self):
return self.message_array
def connect(self, server, ftp_user, ftp_password, is_passive = False):
self.connection_id = FTP.connect(server)
login_result = FTP.login(self.connection_id, ftp_user, ftp_password)
FTP.set_pasv(self.connection_id, is_passive)
if not self.connection_id or not login_result:
self.log_message("FTP Connection has Failed")
self.log_message("Attempted to connect to {0} for {1}".format(server, ftp_user))
return False
else:
self.log_message("Connected to {0} for {1}".format(server, ftp_user))
self.login_ok = True
return True
def make_dir(self, directory):
if FTP.mkd(self.connection_id, directory):
self.log_message("Directory {0} created successfully".format(directory))
return True
else:
self.log_message("Failed creating directory")
return False
def upload_file(self, file_from, file_to):
ascii_array = ['txt','csv']
extension = file_from.split(".")[-1]
if extension in ascii_array:
mode = # FTP_ASCII
else:
mode = # FTP_BINARY
我目前正在测试扩展名是否出现在应作为 ascii 类型上传的文件扩展名列表中。如果它出现在列表中,我们将变量模式设置为 ASCII;否则,我们假设它是二进制类型,并为模式分配值 BINARY。
我怎样才能做到这一点?
请您参考如下方法:
使用storelines对于 ASCII 传输模式,storebinary用于二进制传输模式。
def upload_file(self, file_from, file_to):
if file_from.lower().endswith(('.txt', '.csv')):
with open(file_from, 'r') as f:
self.connection_id.storelines('STOR {}'.format(file_to), f)
else:
with open(file_from, 'rb') as f:
self.connection_id.storebinary('STOR {}'.format(file_to), f)
旁注:您可以使用 str.endswith检查文件扩展名:
>>> 'a.csv'.endswith(('.txt', '.csv'))
True
>>> 'a.txt'.endswith(('.txt', '.csv'))
True
>>> 'a.bin'.endswith(('.txt', '.csv'))
False
顺便说一句,为什么要使用未绑定(bind)的方法 (FTP.login(self.connection_id, ...)) 而不是绑定(bind)方法 (self.connection_id.login(...)) ?
>>> s = "STRING"
>>> str.lower(s) # unbound method
'string'
>>> s.lower() # bound method
'string'
