本文总结一些和ftp服务器相关的python命令。包括登录ftp服务器,进入某个路径,向ftp服务器上传或下载文件,删除ftp上的文件的等。

  1. 代码及注解

# following code are for ftp download/upload files

from ftplib import * 

import os

ftp = FTP("ftpaddress") 

ftp.login("ftpaddress") # login ftp server

ftppath = ftp.cwd("directionary") # cd to directionary which you need do some operation

print ftppath

ftpfolder ftp.nlst("directionary") # list the files in this directionary, return is a list

ftpdir = ftp.dir("directionay") # return the detailed information of this directionary, return is a string

print ftpfolder

print ftpdir

ftp.delete("filename") # delete a file in this directionary

f = open("a file and directionary in locate PC", 'w') # create a file under certain directionary in locate and open with write enable

ftp.retrbinary('RETR + filename', f.write) # ftp download the file to locate directionary

bufsize = 1024

filename = "locate directionary with file need to upload"

file_open= open(filename, "rb")

ftp.storbinary("STOR + filename", file_open,bufsize) # ftp upload file into ftp server

file_open.close()

ftp.quit() # ftp quit after work done

f.close() # close file

 

2. 总结

ftp下载和上传文件的流程是创建ftp连接,登录ftp,cd到需要操作的路径,如果是下载需要在本地创建一个文件并以write enable方式打开/如果是上传文件需要在本地以'rb'方式打开,执行下载/上传命令, 退出ftp,关闭文件。

3. 注意

ftp.nlst 和 ftp.dir的区别,两者返回的值不同, 前者是list, 后者是string。