今天整理了下以前的ftp连接代码:
#coding=utf-8
from ftplib import FTP
import sys
import io
ftp = FTP()
ftp.set_debuglevel(0)
ftp.connect("148.28.19.1",21)
ftp.login("user","password")
ftp.encoding ='gb2312'
ftp.cwd("test\上传") # 改变当前的工作目录
filelist=[]
ftp.retrlines('LIST',filelist.append)
for item in filelist:
print(item)
其中关键的函数是retrlines ,其官方文档的定义是:
FTP.retrlines(cmd, callback=None)
Retrieve a file or directory listing in ASCII transfer mode. cmd should be an appropriate RETR command (see retrbinary()) or a command such as LIST or NLST (usually just the string ‘LIST’). LIST retrieves a list of files and information about those files. NLST retrieves a list of file names. The callback function is called for each line with a string argument containing the line with the trailing CRLF stripped. The default callback prints the line to sys.stdout.
其中cmd命令可以参考这个博客:
https://blog.csdn.net/weiyuefei/article/details/51758288
里面介绍的很详细
总体来说,ftplib封装程度还不够,好多操作需要理解ftp的底层原理。比如上面需要用到ftp的命令。在网上找了下,找到这个人的博客https://www.jianshu.com/p/0255e3ac6691 不过代码排版有些乱,没有测试过是否可用。