下面用一個交互方式演示一下ftplib的主要功能。
>>> from ftplib import FTP
>>> ftp = FTP('ftp.cwi.nl') # connect to host, default port
>>> ftp.login() # user anonymous, passwd anonymous@
>>> ftp.retrlines('LIST') # list directory contents
total 24418
drwxrwsr-x 5 ftp-usr pdmaint 1536 Mar 20 09:48 .
dr-xr-srwt 105 ftp-usr pdmaint 1536 Mar 21 14:32 ..
-rw-r--r-- 1 ftp-usr pdmaint 5305 Mar 20 09:48 INDEX
.
.
.
>>> ftp.retrbinary('RETR README', open('README', 'wb').write)
'226 Transfer complete.'
>>> ftp.quit()
下面一個下載文件的示例
#!/usr/bin/env python
#author:Jims of http://www.ringkee.com/
#create date: 2005/02/05
#description: Using ftplib module download a file from a ftp server.
from ftplib import FTP
ftp=FTP()
ftp.set_debuglevel(2) #打開調(diào)試級別2,顯示詳細(xì)信息
ftp.connect('ftp_server','port') #連接
ftp.login('username','password') #登錄,如果匿名登錄則用空串代替即可
print ftp.getwelcome() #顯示ftp服務(wù)器歡迎信息
ftp.cwd('xxx/xxx/') #選擇操作目錄
bufsize = 1024 #設(shè)置緩沖塊大小
filename='dog.jpg'
file_handler = open(filename,'wb').write #以寫模式在本地打開文件
ftp.retrbinary('RETR dog.jpg',file_handler,bufsize) #接收服務(wù)器上文件并寫入本地文件
ftp.set_debuglevel(0) #關(guān)閉調(diào)試
ftp.quit() #退出ftp服務(wù)器
下面一個上傳文件的示例,要成功運行該腳本,需在ftp服務(wù)器上有上傳文件的權(quán)限。
#!/usr/bin/env python
#author:Jims of http://www.ringkee.com/
#create date: 2005/02/05
#description: Using ftplib module upload a file to a ftp server.
from ftplib import FTP
ftp=FTP()
ftp.set_debuglevel(2)
ftp.connect('ftp_server','port')
ftp.login('username','password')
print ftp.getwelcome()
ftp.cwd('xxx/xxx/')
bufsize = 1024
filename='dog.jpg'
file_handler = open(filename,'rb')
ftp.storbinary('STOR dog.jpg',file_handler,bufsize) #上傳文件
ftp.set_debuglevel(0)
file_handler.close() #關(guān)閉文件
ftp.quit()