Python網(wǎng)絡(luò)編程之ftplib模塊
更新時間:2022年05月31日 08:25:22 作者:springsnow
這篇文章介紹了Python網(wǎng)絡(luò)編程之ftplib模塊,文中通過示例代碼介紹的非常詳細。對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下
Python中默認安裝的ftplib模塊定義了FTP類,可用來實現(xiàn)簡單的ftp客戶端,用于上傳或下載文件。
ftp登陸連接
from ftplib import FTP # 加載ftp模塊
ftp = FTP() # 設(shè)置變量
ftp.set_debuglevel(2) # 打開調(diào)試級別2,顯示詳細信息
ftp.connect("10.126.64.14", 21) # 連接的ftp sever和端口
ftp.login("usr_esop", "PWD4ftp@201903#") # 連接的用戶名,密碼
print(ftp.getwelcome()) # 打印出歡迎信息
ftp.cwd("/ZS_ESOP/55-548410/-/zh/Split") # 更改遠程目錄
bufsize = 1024 # 設(shè)置的緩沖區(qū)大小
filename = "tslint.json" # 需要下載的文件
file_handle = open(filename, "wb").write # 以寫模式在本地打開文件
ftp.retrbinary("RETR tslint.json", file_handle, bufsize) # 接收服務(wù)器上文件并寫入本地文件
ftp.set_debuglevel(0) # 關(guān)閉調(diào)試模式
ftp.quit # 退出ftpftp相關(guān)命令操作
ftp.cwd(pathname) #設(shè)置FTP當前操作的路徑,cwd可以使用“..”,但不使用"./path"以及"../path"這樣的相對路徑
ftp.dir() #顯示目錄下文件信息
ftp.nlst() #獲取目錄下的文件
ftp.mkd(pathname) #新建遠程目錄
ftp.pwd() #返回當前所在位置
ftp.rmd(dirname) #刪除遠程目錄
ftp.delete(filename) #刪除遠程文件
ftp.rename(fromname, toname)#將fromname修改名稱為toname??梢詭窂?,起到移動文件的作用
ftp.storbinaly("STOR filename.txt",file_handel,bufsize) #以
BINARY
模式上傳目標文件
ftp.storlines("STOR filename.txt",file_handel) #以ASCII模式存儲文件
ftp.retrbinary("RETR filename.txt",file_handel,bufsize)#以
BINARY模式
下載FTP文件
FTP.retrlines("RETR filename.txt",file_handel) #以ASCII模式獲取文件或者文件夾列表FTP.quit()與FTP.close()的區(qū)別
- FTP.quit():發(fā)送QUIT命令給服務(wù)器并關(guān)閉掉連接。這是一個比較“緩和”的關(guān)閉連接方式,但是如果服務(wù)器對QUIT命令返回錯誤時,會拋出異常。
- FTP.close():單方面的關(guān)閉掉連接,不應(yīng)該用在已經(jīng)關(guān)閉的連接之后,例如不應(yīng)用在FTP.quit()之后。
下載、上傳文件
from ftplib import FTP
def ftpconnect(host, username, password):
ftp = FTP()
# ftp.set_debuglevel(2) #打開調(diào)試級別2,顯示詳細信息
ftp.encoding = 'GB2312' # 解決中文編碼問題,默認是latin-1,如果將 encoding='utf-8'報錯,可以 改為GB2312、gbk、ISO-8859-1
ftp.connect(host, 21) # 連接
ftp.login(username, password) # 登錄,如果匿名登錄則用空串代替即可
return ftp
def downloadfile(ftp, remotepath, localpath):
bufsize = 1024 # 設(shè)置緩沖塊大小
fp = open(localpath, 'wb') # 以寫模式在本地打開文件
ftp.retrbinary('RETR ' + remotepath, fp.write, bufsize) # 接收服務(wù)器上文件并寫入本地文件
ftp.set_debuglevel(0) # 關(guān)閉調(diào)試
fp.close() # 關(guān)閉文件
def uploadfile(ftp, remotepath, localpath):
bufsize = 1024
fp = open(localpath, 'rb')
ftp.storbinary('STOR ' + remotepath, fp, bufsize) # 上傳文件
ftp.set_debuglevel(0)
fp.close()# 關(guān)閉文件
if __name__ == "__main__":
ftp = ftpconnect("******", "***", "***")
downloadfile(ftp, "***", "***")
uploadfile(ftp, "***", "***")
ftp.quit()上傳、下載文件/目錄
注:目錄內(nèi)為文件,若為目錄則無法傳輸
import os
import ftplib
class myFtp:
ftp = ftplib.FTP()
bIsDir = False
path = ""
def __init__(self, host, port='21'):
# self.ftp.set_debuglevel(2) #打開調(diào)試級別2,顯示詳細信息
# self.ftp.set_pasv(0) #0主動模式 1 #被動模式
self.ftp.encoding = 'GB2312' # 解決中文編碼問題,默認是latin-1,如果將 encoding='utf-8'報錯,可以 改為GB2312、gbk、ISO-8859-1
self.ftp.connect(host, port)
def login(self, user, passwd):
self.ftp.login(user, passwd)
print(self.ftp.welcome)
def down_load_file(self, local_file, remote_file):
file_handler = open(local_file, 'wb')
self.ftp.retrbinary("RETR %s" % remote_file, file_handler.write)
file_handler.close()
return True
def up_load_file(self, local_file, remote_file):
if not os.path.isfile(local_file):
return False
file_handler = open(local_file, "rb")
self.ftp.storbinary('STOR %s' % remote_file, file_handler, 4096)
file_handler.close()
return True
def up_load_file_tree(self, local_dir, remote_dir):
if not os.path.isdir(local_dir):
return False
# print("local_dir:", local_dir)
local_names = os.listdir(local_dir)
# print("list:", local_names)
# print(remote_dir)
self.ftp.cwd(remote_dir)
for Local in local_names:
src = os.path.join(local_dir, Local)
if os.path.isdir(src):
self.up_load_file_tree(src, Local)
else:
self.up_load_file(src, Local)
self.ftp.cwd("..")
return
def down_load_file_tree(self, local_dir, remote_dir):
print("remote_dir:", remote_dir)
if not os.path.isdir(local_dir):
os.makedirs(local_dir)
self.ftp.cwd(remote_dir)
remote_names = self.ftp.nlst()
# print("remote_names", remote_names)
# print(self.ftp.nlst(remote_dir))
for file in remote_names:
local = os.path.join(local_dir, file)
if self.is_dir(file):
self.down_load_file_tree(local, file)
else:
self.down_load_file(local, file)
self.ftp.cwd("..")
return
def show(self, list):
result = list.lower().split(" ")
if self.path in result and "
" in result:
self.bIsDir = True
def is_dir(self, path):
self.bIsDir = False
self.path = path
# this ues callback function ,that will change bIsDir value
self.ftp.retrlines('LIST', self.show)
return self.bIsDir
def close(self):
self.ftp.quit()
if __name__ == "__main__":
ftp = myFtp('10.126.64.14',21)
ftp.login("usr_esop", "PWD4ftp@201903#")
ftp.down_load_file_tree(r"C:\PycharmProjects\untitled\backup", "/ZS_ESOP/55-548410/-/zh/Split") # ok
ftp.up_load_file_tree(r"C:\PycharmProjects\untitled\backup", "/ZS_ESOP/55-548410/-/zh/Split") # ok
ftp.close()
print("ok!")到此這篇關(guān)于Python網(wǎng)絡(luò)編程之ftplib模塊的文章就介紹到這了。希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Python?LeNet網(wǎng)絡(luò)詳解及pytorch實現(xiàn)
LeNet主要用來進行手寫字符的識別與分類,并在美國的銀行中投入了使用。本文主要為大家詳細介紹了LetNet以及通過pytorch實現(xiàn)LetNet,感興趣的小伙伴可以學習一下2021-11-11

