python3 ftp操作

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()

參考

基於python實現FTP文件上傳與下載(ftp&sftp協議)
python3+ftplib實現ftp客戶端

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章