Python教程

python 从FTP目录取文件

本文主要是介绍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:
            #print("file_name:"+file_name)
            ftp_file = os.path.join(ftp_file_path, file_name)
            #print("ftp_file:"+ftp_file)
            write_file = dst_file_path+os.path.basename(file_name)
            #print("write_file:"+write_file)
            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

这篇关于python 从FTP目录取文件的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!