小资料工程师乐园

python: ftplib模板

2020-06-22  本文已影响0人  luffynoonepiece

使用ftplib连接ftp,定义下载和上传函数


# -*- coding:utf-8 -*-

from ftplib import FTP

ftp = FTP()

ftp.set_debuglevel(2)  #打开调试级别2

ftp.connect(host = '',port = )

ftp.login(user = '',passwd = '')

bufsize = 1024 #设置缓存区大小

ftp.set_pasv(False) #关闭被动模式,根据实际需要打开或关闭

print(ftp.getwelcome())

ftp.cwd('/') #切换目录

print(ftp.nlst()) #查看当前目录下的文件

下载函数

def download(path):

    ftp.cwd(path)

    filename = ftp.nlst()

    for i in filename:

        try:

            file_handle = open(i, "wb").write

            #RETR后有一个空格

            ftp.retrbinary("RETR " + i, file_handle, bufsize)#RETR后面有个空格

            print(i)

        except Exception as e:

            print(e)

上传函数

def upload(path):

    ftp.cwd(path)

    filename = ['History.csv']

    for i in filename:

        try:

            localpath = './' + i

            file_handle =  open (localpath, "rb")

            #STOR后有一个空格

            ftp.storbinary("STOR " + i, file_handle, bufsize)

            print(i)

        except Exception as e:

            print(e)

运行

path = ''

download(path)

ftp.quit()

ftp.close()
蟹蟹
上一篇下一篇

猜你喜欢

热点阅读