python 从FTP目录取文件


from ftplib import FTP
import os
class FTP_OP:
    def __init__(self, host, username, password, port , passive):
        self.host = host
        self.username = username
        self.password = password
        self.port = port
        self.pasv = passive
    def ftp_connect(self):
        ftp = FTP()
        ftp.encoding = 'gbk'
        ftp.set_debuglevel(0) 
        ftp.connect(self.host,self.port)
        ftp.login(self.username, self.password) 
        ftp.set_pasv(self.pasv)
        return ftp
    def download_file(self, ftp_file_path, dst_file_path):
        buffer_size = 8192
        ftp = self.ftp_connect()
        print(ftp.getwelcome() )
        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 = dst_file_path+os.path.basename(file_name)
            with open(write_file, "wb") as f:
                ftp.retrbinary('RETR %s' % ftp_file, f.write, buffer_size)
        ftp.quit()
 
if __name__ == '__main__':
    host = "192.168.80.130"
    username = 'ftpuser'
    password = '123456'
    port = 21
    ftp_filefolder = "/test/"  
    dst_filefolder = "d:/1/"  
    ftp = FTP_OP(host, username, password, port,passive = False)
    ftp.download_file(ftp_filefolder, dst_filefolder)

参考

https://docs.python.org/3.6/library/ftplib.html
http://www.cppcns.com/jiaoben/python/368057.html
https://blog.csdn.net/ouyang_peng/article/details/79271113

posted @ 2022-06-04 12:55  shenshu  阅读(1158)  评论(0编辑  收藏  举报