首页 > 代码库 > python之ftplib基础学习
python之ftplib基础学习
# -*- coding: utf-8 -*-
# python:2.x
__author__ = ‘Administrator‘
from ftplib import FTP#加载
#方法或者属性
# ftp=FTP()#变量
# ftp.set_debuglevel(2)#调试级别为2,显示详细信息
# ftp.connect(‘IP‘,‘port‘)#连接ftp服务器和端口
# ftp.login(‘user‘,‘password‘)#连接帐号及密码
# print ftp.getwelcome()#显示信息
# ftp.cmd(‘path‘)#更改远程目录
# bufsize=1024#设置缓冲区大小
# file_handle=open(‘a.txt‘,‘wb‘).writable#以读写模式在本地打开文件
# ftp.retrbinary(‘RETR FILENAME.txt‘,file_handle,bufsize)#接收服务器上文件并写入到本地文件中
# ftp.set_debuglevel(0)#退出调试模式
# ftp.quit#退出
# ftp.cwd(‘pathname‘)#设置当前目录
# ftp.dir()#显示目录文件信息
# ftp.nlst()#获取目录下的文件
# ftp.mkd(‘pathname‘)#新建远程目录
# ftp.pwd()#返回当前所在位置
# ftp.rmd(‘pathname‘)#删除远程目录
# ftp.delete(‘pathname‘)#删除远程文件)
# ftp.rename(‘path1‘,‘path2‘)#重名
# ftp.storbinary(‘stop finename.txt‘,file_handle,bufsize)#上传目录文件
# ftp.retrbinary(‘retr finename.txt‘,file_handle,bufsize)#下载ftp文件
#例子
ftp=FTP()
timeout=30
port=21
ftp.connect(‘192.168.1.111‘,port,timeout)
ftp.login(‘UserName‘,‘888888‘)
print ftp.getwelcome()
ftp.cwd(r‘F:\ftp‘)
l=ftp.nlst()
for name in l:
print name#打印名字
path=r‘F:\ftp‘+name
f=open(path,‘wb‘)
filename=‘RETR‘+name
ftp.retrbinary(‘STOP‘+filename,open(path,‘rb‘))
ftp.quit()
完整模块(是核心编程书籍上的例子)
#!/usr/bin/python
# -*- coding: utf-8 -*-
import ftplib
import os
import socket
HOST = ‘ftp.mozilla.org‘
DIRN = ‘pub/mozilla.org/webtools‘
FILE = ‘bugzilla-3.6.7.tar.gz‘
def main():
try:
f = ftplib.FTP(HOST)
except (socket.error, socket.gaierror):
print ‘ERROR:cannot reach " %s"‘ % HOST
return
print ‘***Connected to host "%s"‘ % HOST
try:
f.login()
except ftplib.error_perm:
print ‘ERROR: cannot login anonymously‘
f.quit()
return
print ‘*** Logged in as "anonymously"‘
try:
f.cwd(DIRN)
except ftplib.error_perm:
print ‘ERRORL cannot CD to "%s"‘ % DIRN
f.quit()
return
print ‘*** Changed to "%s" folder‘ % DIRN
try:
#传一个回调函数给retrbinary() 它在每接收一个二进制数据时都会被调用
f.retrbinary(‘RETR %s‘ % FILE, open(FILE, ‘wb‘).write)
except ftplib.error_perm:
print ‘ERROR: cannot read file "%s"‘ % FILE
os.unlink(FILE)
else:
print ‘*** Downloaded "%s" to CWD‘ % FILE
f.quit()
return
if __name__ == ‘__main__‘:
main()
python之ftplib基础学习