python從FTP下載文件


#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
FTP常用操作
"""
from ftplib import FTP
import os
class FTP_OP(object):
    def __init__(self, host, username, password, port):
        """
        初始化ftp
    :param host: ftp主機ip
    :param username: ftp用戶名
    :param password: ftp密碼
    :param port:  ftp端口 (默認21)
    """
    self.host = host
    self.username = username
    self.password = password
    self.port = port
    def ftp_connect(self):
    """
    連接ftp
    :return:
    """
    ftp = FTP()
    ftp.set_debuglevel(0)  # 不開啟調試模式
    ftp.connect(host=self.host, port=self.port)  # 連接ftp
    ftp.login(self.username, self.password)  # 登錄ftp
    return ftp
    def download_file(self, ftp_file_path, dst_file_path):
    """
    從ftp下載文件到本地
    :param ftp_file_path: ftp下載文件路徑
    :param dst_file_path: 本地存放路徑
    :return:
    """
    buffer_size = 10240  #默認是8192
    ftp = self.ftp_connect()
    print ftp.getwelcome()  #顯示登錄ftp信息
    file_list = ftp.nlst(ftp_file_path)
    for file_name in file_list:
        ftp_file = os.path.join(ftp_file_path, file_name)
        write_file = os.path.join(dst_file_path, file_name)
        print file_name
        if file_name.find('.jpg')>-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 {0}'.format(ftp_file), f.write, buffer_size)
                f.close()
    ftp.quit()

if __name__ == '__main__':
    host = "10.201.xx.xx"
    username = "xxx"
    password = "xxx"
    port = "9999"
    ftp_file_path = "/upload/20160726"
    dst_file_path = "/home/gdmt/master/py/tmp"
    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)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM