python內建有ftp編程的模組ftplib
直接貼幾行程式碼分析
import os, sysfrom ftplib import FTPftpsite = "ftp.site"userinfo = ('aaron', getpass('123456'))print('Connecting')connection = ftplib.FTP(sitename)connnection.login(*userinfo) ##() for anonymous loginconnection.nlst() ##nlst() gives files list ##dir() gives full details) connection.cwd(".") ##cd to directoryfilename = 'filename'##########download a file#############localfile = open(filename, 'wb') ##local file to store downloadconnection.retrbinary('RETR ' + filename, localfile.write, 1024)localfile.close()##########download a file#######################upload a file#############localfiletoupload = open(filename, 'rb')connection.storbinary('STOR ' + filename, localfiletoupload, 1024)##########upload a file#############connection.quit()
上面的代碼未經測試!
主要是列舉幾個常見的操作:
登入ftp網站:
connection = ftplib.FTP(sitename)connnection.login(*userinfo) ##() for anonymous login
nlst() #擷取檔案清單
retrbinary() #下載檔案
storbinary() #上傳檔案
cwd('dir') #切換到目錄
只列舉這幾個,其它一些操作查看help()
推薦一本python書:python programming(這本書沒有講python基礎文法,應用涵蓋情境比較廣,建議有一點python基礎的人看)
connection = ftplib.FTP(sitename)connnection.login(*userinfo) ##() for anonymous login