ftp简介
FTP(File Transfer Protocol)是文件传输协议的简称。用于Internet上的控制文件的双向传输。同时,它也是一个应用程序(Application)。用户可以通过它把自己的PC机与世界各地所有运行FTP协议的服务器相连,访问服务器上的大量程序和信息。如果用户需要将文件从自己的计算机上发送到另一台计算机上,可使用FTP上传(upload)或(put)操作,而更多种的情况是用户使用FTP下载(download)或获取(get)操作从FTP服务器上下载文件,python通过ftplib来实现其功能。
常用ftp命令与函数对应关系
ftp命令 | 对应的FTP对象方法 | 备注 |
---|---|---|
ls | nlst([pathname]) | Return a list of file names as returned by the NLST command. |
dir | dir([pathname]) | Produce a directory listing as returned by the LIST command, printing it to standard output. |
rename | rename(fromname, toname) | Rename file fromname on the server to toname. |
delete | delete(filename) | Remove the file named filename from the server. |
cd | cwd(pathname) | Set the current directory on the server. |
mkdir | mkd(pathname) | Create a new directory on the server. |
pwd | pwd() | Return the pathname of the current directory on the server. |
rmdir | rmd(dirname) | Remove the directory named dirname on the server. |
size(filename) | Request the size of the file named filename on the server. | |
quit | quit() | Send a QUIT command to the server and close the connection. |
close | close() | Close the connection unilaterally. |
put | storbinary(cmd, fp, blocksize=8192, callback=None, rest=None) | Store a file in binary transfer mode. |
get | retrbinary(cmd, callback, blocksize=8192, rest=None) | Retrieve a file in binary transfer mode. |
实例
from ftplib import FTP
# 创建FTP对象,设置调试级别
ftp = FTP()
ftp.set_debuglevel(2)
# 连接FTP并打印出欢迎信息
ftp.connect("IP","port")
ftp.login("user","password")
print ftp.getwelcome()
# 进入远程目录
ftp.cmd("xxx/xxx")
# 设置的缓冲区大小
bufsize=1024
# 上传文件
file_handler = open("file1.txt","rb")
ftp.storbinaly("STOR filename1.txt", file_handler, bufsize)
file_handler.close()
# 下载文件
file_handler = open("fil2.txt", "wb")
ftp.retrbinary("RETR file2.txt", file_handler.write, bufsize)
file_handler.close()
#关闭调试模式, 退出ftp
ftp.set_debuglevel(0)
ftp.quit()