• DAY 204 python FTP上传和下载文件


    1. 连接FTP server

    import ftplib
    ftp = ftplib.FTP(ftpserver, user, passwd)

    等同于

    import ftplib
    ftp = ftplib.FTP()
    ftp.connect(ftpserver)
    ftp.login(user,passwd)

        对于初始化函数FTP(),如果指定host,则自动调用connect函数,如果指定了user和passwd,则自动调用login,如果都没指定,就什么都不做,需要显示调用。

    2. upload

    复制代码
    import ftplib
    
    def uploadToFTP(filename, targetdir, ftpserver, user="user", passwd="123"):
        rtd = 0
        targetdir = targetdir.split(ftpserver)[-1] # remove ftpserver string from targetdir string if contain
        fp = open(filename, 'rb')
        ftp = ftplib.FTP(ftpserver, user, passwd) # make connection and login FTP
        try:
            ftp.cwd(targetdir)
        except ftplib.error_perm:
            print "Error: cannot upload to FTP, no such folder"
            return -2
        try:
            ftp.storbinary('STOR %s/%s'%(targetdir,filename), fp)
        except Exception, e:
            traceback.print_exc()
            rtd = 1
        finally:
            fp.close()
            ftp.quit()
        return rtd
    复制代码

    3. download

    复制代码
    # ftp.retrbinary(cmd, callback, blocksize=8192, rest=None)
    
    def downloadfile()  
        remotepath = "/home/pub/dog.jpg";  
        localpath = 'f:\test\dog.jpg'  
        fp = open(localpath,'wb') #以写模式在本地打开文件
    
        ftp.retrbinary('RETR ' + remotepath,fp.write,bufsize) #接收服务器上文件并写入本地文件  
    
        ftp.set_debuglevel(0) #关闭调试  
        fp.close()  
        ftp.quit() #退出ftp服务器
    复制代码
  • 相关阅读:
    HUST 1372 marshmallow
    HUST 1371 Emergency relief
    CodeForces 629D Babaei and Birthday Cake
    CodeForces 629C Famil Door and Brackets
    ZOJ 3872 Beauty of Array
    ZOJ 3870 Team Formation
    HDU 5631 Rikka with Graph
    HDU 5630 Rikka with Chess
    CodeForces 626D Jerry's Protest
    【POJ 1964】 City Game
  • 原文地址:https://www.cnblogs.com/DEJAVU888/p/15303185.html
Copyright © 2020-2023  润新知