python實(shí)現(xiàn)支持目錄FTP上傳下載文件的方法
本文實(shí)例講述了python實(shí)現(xiàn)支持目錄FTP上傳下載文件的方法。分享給大家供大家參考。具體如下:
該程序支持ftp上傳下載文件和目錄、適用于windows和linux平臺(tái)。
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import ftplib
import os
import sys
class FTPSync(object):
conn = ftplib.FTP()
def __init__(self,host,port=21):
self.conn.connect(host,port)
def login(self,username,password):
self.conn.login(username,password)
self.conn.set_pasv(False)
print self.conn.welcome
def test(self,ftp_path):
print ftp_path
print self._is_ftp_dir(ftp_path)
#print self.conn.nlst(ftp_path)
#self.conn.retrlines( 'LIST ./a/b')
#ftp_parent_path = os.path.dirname(ftp_path)
#ftp_dir_name = os.path.basename(ftp_path)
#print ftp_parent_path
#print ftp_dir_name
def _is_ftp_file(self,ftp_path):
try:
if ftp_path in self.conn.nlst(os.path.dirname(ftp_path)):
return True
else:
return False
except ftplib.error_perm,e:
return False
def _ftp_list(self, line):
list = line.split(' ')
if self.ftp_dir_name==list[-1] and list[0].startswith('d'):
self._is_dir = True
def _is_ftp_dir(self,ftp_path):
ftp_path = ftp_path.rstrip('/')
ftp_parent_path = os.path.dirname(ftp_path)
self.ftp_dir_name = os.path.basename(ftp_path)
self._is_dir = False
if ftp_path == '.' or ftp_path== './' or ftp_path=='':
self._is_dir = True
else:
#this ues callback function ,that will change _is_dir value
try:
self.conn.retrlines('LIST %s' %ftp_parent_path,self._ftp_list)
except ftplib.error_perm,e:
return self._is_dir
return self._is_dir
def get_file(self,ftp_path,local_path='.'):
ftp_path = ftp_path.rstrip('/')
if self._is_ftp_file(ftp_path):
file_name = os.path.basename(ftp_path)
#如果本地路徑是目錄,下載文件到該目錄
if os.path.isdir(local_path):
file_handler = open(os.path.join(local_path,file_name), 'wb' )
self.conn.retrbinary("RETR %s" %(ftp_path), file_handler.write)
file_handler.close()
#如果本地路徑不是目錄,但上層目錄存在,則按照本地路徑的文件名作為下載的文件名稱
elif os.path.isdir(os.path.dirname(local_path)):
file_handler = open(local_path, 'wb' )
self.conn.retrbinary("RETR %s" %(ftp_path), file_handler.write)
file_handler.close()
#如果本地路徑不是目錄,且上層目錄不存在,則退出
else:
print 'EROOR:The dir:%s is not exist' %os.path.dirname(local_path)
else:
print 'EROOR:The ftp file:%s is not exist' %ftp_path
def put_file(self,local_path,ftp_path='.'):
ftp_path = ftp_path.rstrip('/')
if os.path.isfile( local_path ):
file_handler = open(local_path, "r")
local_file_name = os.path.basename(local_path)
#如果遠(yuǎn)程路徑是個(gè)目錄,則上傳文件到這個(gè)目錄,文件名不變
if self._is_ftp_dir(ftp_path):
self.conn.storbinary('STOR %s'%os.path.join(ftp_path,local_file_name), file_handler)
#如果遠(yuǎn)程路徑的上層是個(gè)目錄,則上傳文件,文件名按照給定命名
elif self._is_ftp_dir(os.path.dirname(ftp_path)):
print 'STOR %s'%ftp_path
self.conn.storbinary('STOR %s'%ftp_path, file_handler)
#如果遠(yuǎn)程路徑不是目錄,且上一層的目錄也不存在,則提示給定遠(yuǎn)程路徑錯(cuò)誤
else:
print 'EROOR:The ftp path:%s is error' %ftp_path
file_handler.close()
else:
print 'ERROR:The file:%s is not exist' %local_path
def get_dir(self,ftp_path,local_path='.',begin=True):
ftp_path = ftp_path.rstrip('/')
#當(dāng)ftp目錄存在時(shí)下載
if self._is_ftp_dir(ftp_path):
#如果下載到本地當(dāng)前目錄下,并創(chuàng)建目錄
#下載初始化:如果給定的本地路徑不存在需要?jiǎng)?chuàng)建,同時(shí)將ftp的目錄存放在給定的本地目錄下。
#ftp目錄下文件存放的路徑為local_path=local_path+os.path.basename(ftp_path)
#例如:將ftp文件夾a下載到本地的a/b目錄下,則ftp的a目錄下的文件將下載到本地的a/b/a目錄下
if begin:
if not os.path.isdir(local_path):
os.makedirs(local_path)
local_path=os.path.join(local_path,os.path.basename(ftp_path))
#如果本地目錄不存在,則創(chuàng)建目錄
if not os.path.isdir(local_path):
os.makedirs(local_path)
#進(jìn)入ftp目錄,開(kāi)始遞歸查詢
self.conn.cwd(ftp_path)
ftp_files = self.conn.nlst()
for file in ftp_files:
local_file = os.path.join(local_path, file)
#如果file ftp路徑是目錄則遞歸上傳目錄(不需要再進(jìn)行初始化begin的標(biāo)志修改為False)
#如果file ftp路徑是文件則直接上傳文件
if self._is_ftp_dir(file):
self.get_dir(file,local_file,False)
else:
self.get_file(file,local_file)
#如果當(dāng)前ftp目錄文件已經(jīng)遍歷完畢返回上一層目錄
self.conn.cwd( ".." )
return
else:
print 'ERROR:The dir:%s is not exist' %ftp_path
return
def put_dir(self,local_path,ftp_path='.',begin=True):
ftp_path = ftp_path.rstrip('/')
#當(dāng)本地目錄存在時(shí)上傳
if os.path.isdir(local_path):
#上傳初始化:如果給定的ftp路徑不存在需要?jiǎng)?chuàng)建,同時(shí)將本地的目錄存放在給定的ftp目錄下。
#本地目錄下文件存放的路徑為ftp_path=ftp_path+os.path.basename(local_path)
#例如:將本地文件夾a上傳到ftp的a/b目錄下,則本地a目錄下的文件將上傳的ftp的a/b/a目錄下
if begin:
if not self._is_ftp_dir(ftp_path):
self.conn.mkd(ftp_path)
ftp_path=os.path.join(ftp_path,os.path.basename(local_path))
#如果ftp路徑不是目錄,則創(chuàng)建目錄
if not self._is_ftp_dir(ftp_path):
self.conn.mkd(ftp_path)
#進(jìn)入本地目錄,開(kāi)始遞歸查詢
os.chdir(local_path)
local_files = os.listdir('.')
for file in local_files:
#如果file本地路徑是目錄則遞歸上傳目錄(不需要再進(jìn)行初始化begin的標(biāo)志修改為False)
#如果file本地路徑是文件則直接上傳文件
if os.path.isdir(file):
ftp_path=os.path.join(ftp_path,file)
self.put_dir(file,ftp_path,False)
else:
self.put_file(file,ftp_path)
#如果當(dāng)前本地目錄文件已經(jīng)遍歷完畢返回上一層目錄
os.chdir( ".." )
else:
print 'ERROR:The dir:%s is not exist' %local_path
return
if __name__ == '__main__':
ftp = FTPSync('192.168.1.110')
ftp.login('test','test')
#上傳文件,不重命名
#ftp.put_file('111.txt','a/b')
#上傳文件,重命名
#ftp.put_file('111.txt','a/112.txt')
#下載文件,不重命名
#ftp.get_file('/a/111.txt',r'D:\\')
#下載文件,重命名
#ftp.get_file('/a/111.txt',r'D:\112.txt')
#下載到已經(jīng)存在的文件夾
#ftp.get_dir('a/b/c',r'D:\\a')
#下載到不存在的文件夾
#ftp.get_dir('a/b/c',r'D:\\aa')
#上傳到已經(jīng)存在的文件夾
ftp.put_dir('b','a')
#上傳到不存在的文件夾
ftp.put_dir('b','aa/B/')
希望本文所述對(duì)大家的Python程序設(shè)計(jì)有所幫助。
- Python 使用SFTP和FTP實(shí)現(xiàn)對(duì)服務(wù)器的文件下載功能
- python從ftp獲取文件并下載到本地
- python實(shí)現(xiàn)從ftp上下載文件的實(shí)例方法
- 基于python實(shí)現(xiàn)FTP文件上傳與下載操作(ftp&sftp協(xié)議)
- python實(shí)現(xiàn)從ftp服務(wù)器下載文件
- Python FTP文件定時(shí)自動(dòng)下載實(shí)現(xiàn)過(guò)程解析
- python2.7實(shí)現(xiàn)FTP文件下載功能
- python實(shí)現(xiàn)下載整個(gè)ftp目錄的方法
- python實(shí)現(xiàn)的簡(jiǎn)單FTP上傳下載文件實(shí)例
- Python實(shí)現(xiàn)FTP文件定時(shí)自動(dòng)下載的步驟
相關(guān)文章
python畫(huà)圖常見(jiàn)不同圖片格式保存方式
這篇文章主要介紹了python畫(huà)圖常見(jiàn)不同圖片格式保存方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-09-09
scrapy結(jié)合selenium解析動(dòng)態(tài)頁(yè)面的實(shí)現(xiàn)
這篇文章主要介紹了scrapy結(jié)合selenium解析動(dòng)態(tài)頁(yè)面的實(shí)現(xiàn),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2020-09-09
python神經(jīng)網(wǎng)絡(luò)pytorch中BN運(yùn)算操作自實(shí)現(xiàn)
這篇文章主要為大家介紹了python神經(jīng)網(wǎng)絡(luò)pytorch中BN運(yùn)算操作自實(shí)現(xiàn)示例,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-05-05
使用Python解析JSON的實(shí)現(xiàn)示例
本文主要介紹了使用Python解析JSON的實(shí)現(xiàn)示例,文中通過(guò)示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-12-12
Python中性能分析利器pyinstrument詳細(xì)講解
大家好,本篇文章主要講的是Python中性能分析利器pyinstrument詳細(xì)講解,感興趣的同學(xué)趕快來(lái)看一看吧,對(duì)你有幫助的話記得收藏一下2022-02-02

