python标准库:ftplib模块

ftplib模块包含了文件传输协议(FTP)客户端的实现。

下面的例子展示了如何登入和获取进入目录的列表,dir函数传入一个回调函数,该回调函数在服务器相应时每一行调用一次。ftplib模块默认的回调函数简单的把相应打到sys.stdout下。

值得注意的是目录列表的格式是和服务器相关的(通常来讲获取的目录形式和服务器平台的形式是一样的)。

例子:使用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

结果如下:

$ 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模块检索文件

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")

结果如下:

$ 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服务器上。这个脚本使用文件扩展来确认文件是文本文件还是二进制文件。

例子:使用ftplib模块存储文件

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基础教程

猜你喜欢

转载自blog.csdn.net/weixin_40425640/article/details/79925521