python ftp get file and downloaded to the local

Recently, demand is the need to address the other pictures on the ftp to provide access to the local server, originally planned thinking is to use shell operations, because the shell itself also supports ftp commands in a for loop can achieve demand. But then thinking about or take python operation; then proceeds Baidu online; without exception, was so disappointed to not be directly copied to use. Thus in a modified code. Still a little heart to learn things; as long as the specific operation code ftp account password has been modified to use the corresponding directory

It should be noted at this point to note is os.path.join usage

! # / usr / bin / Python 
# - * - Coding: UTF-. 8 - * -
"" "
the FTP common operation
" ""
from ftplib Import the FTP
Import OS
class FTP_OP (Object):
DEF the __init __ (Self, Host, username, password, port):
"" "
initialize the FTP
: param host: the FTP host ip
: username param: the FTP username
: param password: ftp password
: param port: ftp port (default 21) "
""
self.host = host
Self. username = username
self.password = password
self.port = Port
DEF FTP_CONNECT (Self):
"" "
connected FTP
: return:
" ""
ftp = FTP()
ftp.set_debuglevel (1) # no debug mode is turned
ftp.connect (host = self.host, port = self.port) # connect the FTP
ftp.login (self.username, self.password) # Log in the FTP
ftp.set_pasv (False ) ## ftp there are active and passive mode needs to be adjusted
return ftp
DEF download_file (Self, ftp_file_path, dst_file_path):
"" "
from the ftp download to your
: param ftp_file_path: ftp download file path
: param dst_file_path: local storage path
: return:
" ""
buffer_size = 102400 # default is 8192
ftp = self.ftp_connect ()
Print (ftp.getwelcome ()) # ftp login information
file_list = ftp.nlst (ftp_file_path)
for file_name in file_list:
print("file_name"+file_name)
ftp_file = os.path.join(ftp_file_path, file_name)
print("ftp_file:"+ftp_file)
#write_file = os.path.join(dst_file_path, file_name)
write_file = dst_file_path+file_name ##在这里如果使用os.path.join 进行拼接的话 会丢失dst_file_path路径,与上面的拼接路径不一样
print("write_file"+write_file)
if file_name.find('.png')>-1 and not os.path.exists(write_file):
print("file_name:"+file_name)
#ftp_file = os.path.join(ftp_file_path, file_name)
#write_file = os.path.join(dst_file_path, file_name)
with open(write_file, "wb") as f:
ftp.retrbinary('RETR %s' % ftp_file, f.write, buffer_size)
#f.close()
ftp.quit()

if __name__ == '__main__':
host = "192.168.110.**"
username = "****"
password = "****"
port = 21
ftp_file_path = "/erp-mall/" #FTP目录
dst_file_path = "/root/11" #本地目录
ftp = FTP_OP(host=host, username=username, password=password, port=port)
ftp.download_file(ftp_file_path=ftp_file_path, dst_file_path=dst_file_path)

Guess you like

Origin www.cnblogs.com/coolIt/p/12568975.html