2.3 利用FTP服务器下载和上传文件

本文介绍了如何使用Python的FTP模块实现文件从FTP服务器上的下载与上传功能。通过具体示例代码展示了getfile函数用于下载指定文件,putfile函数用于上传本地文件到服务器。

二.利用FTP服务器的下载文件

from ftplib import FTP
from os.path import exists

def getfile(file,site,dir,user=(),*,verbose=True,refetch=False):       #verbose为是否打印信息,refetch为是否重新获取文件
    if exists(file) and not refetch:
        if verbose: print(file,'already fetched')
    else:
        if verbose:print('Downloading',file)
        local = open(file,'wb')
        try:
            remote = FTP(site)
            remote.login(*user)
            remote.cwd(dir)
            remote.retrbinary('RETR ' + file, local.write, 1024)
            remote.quit()
            if verbose: print('Finished')
        finally:
            local.close()


if __name__ == '__main__':
    file = 'new_1.py'
    dir = '.'
    site = '192.168.191.1'
    user = ()
    getfile(file,site,dir,user)

 

二.利用FTP服务器的上传文件

import ftplib

def putfile(file,site,dir,user=(),*,verbose=True):
    if verbose: print('Uploading',file)
    local = open(file,'rb')
    remote = ftplib.FTP(site)
    remote.login(*user)
    remote.cwd(dir)
    remote.storbinary('STOR ' + file,local,1024)
    remote.quit()
    local.close()
    if verbose: print('Upload done')

if __name__ == '__main__':
    file = 'test.py'
    dir = '.'
    site = '192.168.191.1'
    user = ()
    putfile(file, site, dir, user)

 

转载于:https://www.cnblogs.com/fg2312/p/7637061.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值