Python_ftplib to download files via FTP

Source: Internet
Author: User
Tags ftp connection ftp file ftp login ftp client

1. Ftplib Common Function Introduction

In Python, the default installation of the Ftplib module defines the FTP class, where functions are limited, can be used to implement a simple FTP client, for uploading or downloading files, the main introduction of connection to FTP and file download function, can be used to automate the deployment of file download, log file download, etc.

1.1 Loading the FTP module
From Ftplib import FTP or import ftplib, you need to load the FTP module before the function is written
1.2 Setting variables

FTP = FTP (), a person feels like a destructor, that is, you need to specify a variable as an FTP variable when defining a variable

1.3 Connecting to the FTP server

Ftp.connect (host= ", port=0, timeout=-999), can also be ftp.connect (host=", port=0) using the default time-out, be sure to pay attention to the properties of the parameters when using, port is not str type, The definition should be port=21 and not port= ' 21 '

1.4 Login FTP

Ftp.login ("User", "password"), log in to FTP using your account password

1.5 Opening the debug level

Ftp.set_debuglevel (2) to open debug Level 2, show details, divided into 3 levels, respectively, so turn off debug level to Ftp.set_debuglevel (0)

0:no debugging output (default)

1:print commands and responses but not body text etc.

2:also print raw lines read and sent before stripping cr/lf "

1.6 Print out the welcome message

Print Ftp.getwelcome (), it is recommended to use this function to see if login is successful after FTP login is completed

1.7 Setting the path of the FTP current operation

FTP.CWD (pathname) to set the current operation path for FTP

1.8 Downloading FTP files

Ftp.retrbinary ("RETR filename.txt", open (filename, "WB"). Write,bufsize) is used to download the ftp file and save the file in a local file

1.9 Exiting FTP

Ftp.quit for exiting FTP logins

1.10 Other Method Descriptions

Ftp.cmd ("xxx/xxx") #更改远程目录

Open (filename, WB). Write #以写模式在本地打开文件

Ftp.dir () #显示目录下文件信息

Ftp.nlst () #获取目录下的文件

FTP.MKD (pathname) #新建远程目录

Ftp.pwd () #返回当前所在位置

FTP.RMD (dirname) #删除远程目录

Ftp.delete (filename) #删除远程文件

Ftp.rename (FromName, ToName) #将fromname修改名称为toname.

Ftp.storbinaly ("STOR filename.txt", file_handel,bufsize) #上传目标文件

2. Case Introduction
#-*-coding:utf-8-*-__author__='Test'#!/usr/bin/python fromftplib Import FTP #加载FTP模块import sys,os,socket# define the parameters associated with the FTP connection Const_host=''#定义常量保存ftp服务器ipCONST_PORT= +Const_timeout= -Const_username='Test'const_pwd='Test'#定义与项目相关的参数CONST_PRONAME='Proname'Const_localpath='e:\\ftptest\\'#定义文件下载保存到本地的路径CONST_VERSIONNUM='Versionnum'#定义自动构建本次的版本号, and path stitching form file download path filename='Test.rar'#定义需要下载的文件名称buffersize=1024x768#设置缓冲区大小ftp=FTP () #设置变量def ftpconnect (): #定义ftp连接方法Try: Ftp.connect (const_host,const_port,const_timeout) #连接ftp服务器 except (socket.error,socket.gaierror): PR Int ('Error:cannot reach%s'%const_host) Sys.exit (0)        return    Else: Print ('***connected to host%s'%const_host)Try: Ftp.login (const_username,const_pwd) #登录ftp #ftp. Set_debuglevel (2) #打开调试级别2, show details except Ftplib.error_perm:print ('Error:cannot Login%s'%const_host +'Please check the host,username and password!') Ftpdisconnect ()return    Else: Print ('* * * Logged in%s'%const_host) Print ftp.getwelcome () #获得欢迎信息returnftpdef ftpdisconnect (): Ftp.quit () #退出FTP服务器def downloadfile (): Versionnum= Raw_input ("Please enter this deployment version number:") RemotePath= Const_proname +'/11.tags/build'+ Versionnum +'/release/'#定义ftp的路径 LocalPath= Const_localpath +filename #定义本地保存的文件路径 #Set the path to FTP * * *Try: FTP.CWD (RemotePath) except Ftplib.error_perm:print ('ERROR cannot CD to%s'%RemotePath) ftpdisconnect ()return    Else: Print ('* * * Check file from folder%s'%RemotePath) #***pass a callback function to Retrbinary () it will be called every time a binary data is receivedTry: F= Open (LocalPath,'WB') #打开要保存的文件, F.write is to open the locally saved file in write mode ftp.retrbinary ('RETR%s'%filename,f.write,buffersize) #接收服务器上文件并保存在本地文件 except Ftplib.error_perm:print ('error:cannot Read file%s'%filename) os.unlink (filename)Else: Print ('* * * Downloaded%s to'%filename + Const_localpath +'Success') F.close () #ftp. Set_debuglevel (0) #关闭调试模式returnif__name__ = ="__main__": Ftpconnect () DownloadFile () Ftpdisconnect ( )
3. More than 3.1 lines of comments are described in common commands

Select the line you want to comment on, ctrl+/

3.2 Canceling multiple lines of comment

Select the line that you want to uncomment, ctrl+/

3.3 Viewing methods using

You can see the type of the function definition parameter by holding down CTRL and clicking directly on the functions name.

4. References


Python_ftplib to download files via FTP

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.