python標準庫:ftplib模塊

ftplib模塊包含了文件傳輸協議(FTP)客戶端的實現。html

下面的例子展現瞭如何登入和獲取進入目錄的列表,dir函數傳入一個回調函數,該回調函數在服務器相應時每一行調用一次。ftplib模塊默認的回調函數簡單的把相應打到sys.stdout下。python

值得注意的是目錄列表的格式是和服務器相關的(一般來說獲取的目錄形式和服務器平臺的形式是同樣的)。編程

例子:使用ftplib模塊獲取文件夾列表服務器

import ftplib

ftp = ftplib.FTP("www.python.org")
ftp.login("anonymous", "ftplib-example-1")

data = []

ftp.dir(data.append)

ftp.quit()

for line in data:
    print "-", line

結果以下:app

$ python ftplib-example-1.py
- total 34
- drwxrwxr-x  11 root     4127         512 Sep 14 14:18 .
- drwxrwxr-x  11 root     4127         512 Sep 14 14:18 ..
- drwxrwxr-x   2 root     4127         512 Sep 13 15:18 RCS
- lrwxrwxrwx   1 root     bin           11 Jun 29 14:34 README -> welcome.msg
- drwxr-xr-x   3 root     wheel        512 May 19  1998 bin
- drwxr-sr-x   3 root     1400         512 Jun  9  1997 dev
- drwxrwxr--   2 root     4127         512 Feb  8  1998 dup
- drwxr-xr-x   3 root     wheel        512 May 19  1998 etc
...

文件下載較爲簡單,恰當的使用retr函數,在下載文本文件的時候要注意,你本身須要添加文件結束。下面的函數使用lambda表達式可以快速的完成添加文件結尾。函數

例子:使用ftplib模塊檢索文件fetch

import ftplib
import sys

def gettext(ftp, filename, outfile=None):
    # fetch a text file
    if outfile is None:
        outfile = sys.stdout
    # use a lambda to add newlines to the lines read from the server
    ftp.retrlines("RETR " + filename, lambda s, w=outfile.write: w(s+"\n"))

def getbinary(ftp, filename, outfile=None):
    # fetch a binary file
    if outfile is None:
        outfile = sys.stdout
    ftp.retrbinary("RETR " + filename, outfile.write)

ftp = ftplib.FTP("www.python.org")
ftp.login("anonymous", "ftplib-example-2")

gettext(ftp, "README")
getbinary(ftp, "welcome.msg")

結果以下:ui

$ python ftplib-example-2.py
WELCOME to python.org, the Python programming language home site.

You are number %N of %M allowed users.  Ni!

Python Web site: http://www.python.org/

CONFUSED FTP CLIENT?  Try begining your login password with '-' dash.
This turns off continuation messages that may be confusing your client.
...

最後,以下的例子是拷貝文件到FTP服務器上。這個腳本使用文件擴展來確認文件是文本文件仍是二進制文件。code

例子:使用ftplib模塊存儲文件server

import ftplib
import os

def upload(ftp, file):
    ext = os.path.splitext(file)[1]
    if ext in (".txt", ".htm", ".html"):
        ftp.storlines("STOR " + file, open(file))
    else:
        ftp.storbinary("STOR " + file, open(file, "rb"), 1024)

ftp = ftplib.FTP("ftp.fbi.gov")
ftp.login("mulder", "trustno1")

upload(ftp, "trixie.zip")
upload(ftp, "file.txt")
upload(ftp, "sightings.jpg")

轉載請標明來之:阿貓學編程

更多教程:阿貓學編程-python基礎教程

相關文章
相關標籤/搜索