您的位置:首页 > 编程语言 > Python开发

[python] 使用ftplib模块在交互式窗口下连接FTP的练习

2013-09-25 16:53 302 查看
ftplib是 Python的内置的一个标准模块,它提供了极强大的对FTP服务器的操作,通过它我们可以连接并操作FTP服务端,开始练习:

一、导入模块并进行连接

>>> from ftplib import FTP

>>> ftp = FTP(‘ftp.yabogo.com’)

>>> ftp.login(‘yourloginname’,'password’)





FTP登录成功

连接到FTP可还有如下形式:

1、实例化并直接连接,ftp=FTP(host=”, user=”, passwd=”, acct=”, timeout=”)

2、先实例ftp=FTP(), 再使用 connect(host=”, port=0, timeout=-999)连接,最后login(user=”, passwd=”)

二、查看目录文件或更改目录

>>> ftp.retrlines(‘LIST’)





.retrlines('LIST')结果

1、retrlines(cmd)是以文本形式查看当前目录文件,可用cmd:RETR, LIST, NLST, MLSD

2、如果要指定查看某个目录的文件列表,可以用dir(dirname) ,dirname是可选参数,默认是当前目录;

3、cwd(dirname), 更改目录! Change to a directory.

三、查看文件的大小

>>> ftp.size(‘yabogo_logo.gif’)

2452

四、上传一个文件

>>> fp=open(‘F:/test.php’,'rb’)

>>> ftp.storbinary(‘STOR test.php’,fp)



二进上传文件成功

storbinary( cmd, fp, blocksize=8192, callback=None, rest=None)

Args:

cmd: A STOR command.

fp: A file-like object with a read(num_bytes) method.

blocksize: The maximum data size to read from fp and send over

the connection at once. [default: 8192]

callback: An optional single parameter callable that is called on

on each block of data after it is sent. [default: None]

rest: Passed to transfercmd(). [default: None]

Returns:

The response code.

五、退出关闭,并退出FTP

>>> ftp.quit()

’221 Goodbye, logging out.’

ftplib有很多可用的方法,导入模块后可通过help()查看帮助信息。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: