coding:utf-8
import ftplib
import os
import datetime
import sys
连接ftp
class FtpFunction():
# 开启资源
def init(self, host, port, userName, passWord, TimeOut, Encode):
self.ftp = ftplib.FTP()
self.ftp.connect(host, port, TimeOut)
self.ftp.login(userName, passWord)
# 更改编码格式(gbk utf-8)
self.ftp.encoding = Encode
# 辅助函数
def linux_ls(self, local_path):
try:
list_dir = os.listdir(local_path)
except Exception as e:
print(e)
print('该文件夹下没有文件')
list_dir = []
print(list_dir)
return list_dir
# 创建建文件夹
def mkdir(self, fileName):
try:
self.ftp.mkd(fileName)
except Exception as e:
print(e)
def cd(self, path):
# 转换目录
try:
self.ftp.cwd(path)
except Exception as e:
print(e)
# 删除文件夹/文件
def delete(self, file_path):
try:
self.ftp.rmd(file_path)
except Exception as e:
print(e)
self.ftp.delete(file_path)
# 当前路径
def pwd(self):
path = self.ftp.pwd()
print(path)
# 查看当前目录下的文件
def ls(self):
all_filename = self.ftp.nlst()
# for filename in all_filename:
# print(filename)
return all_filename
# 上传文件
def put(self, local_path, put_path):
self.mkdir(put_path)
self.cd(put_path)
bufsize = 1024
filename = local_path.split('/')[-1]
fp = open(local_path, 'rb')
try:
command_result = self.ftp.storbinary(f'stor {filename}', fp, bufsize)
print(command_result, '上传成功', f' 目前文件夹下文件数量:{len(self.ls())}')
except Exception as e:
print(e)
# 上传文件夹
def put_dir(self, local_path, put_path):
self.mkdir(put_path)
self.cd(put_path)
local_path_list = self.linux_ls(local_path)
bufsize = 1024
for filename in local_path_list:
# 上传文件;'stor ftp_client.py'告诉服务端将上传的文件保存为ftp_client.py,open()是以二进制读方式打开本地要上传的文件
try:
with open(local_path + filename, 'rb') as fp:
command_result = self.ftp.storbinary(f'stor {filename}', fp, bufsize)
print(command_result, '上传成功', f' 目前文件夹下文件数量:{len(self.ls())}')
except Exception as e:
print(e)
# 下载文件
def get(self, local_path, get_path):
is_exists = os.path.exists(local_path) # 是否存在该目录
if not is_exists:
os.makedirs(local_path)
print('{0} creat successful!'.format(local_path))
else:
pass
bufsize = 1024
filename = get_path.split('/')[-1]
self.cd(get_path.split(filename)[0])
try:
with open(local_path + filename, 'wb') as fp:
command_result = self.ftp.retrbinary(f'RETR {filename}', fp.write, bufsize)
print(command_result, '下载成功')
except Exception as e:
print(e)
# 下载文件夹
def get_dir(self, local_path, get_path):
is_exists = os.path.exists(local_path) # 是否存在该目录
if not is_exists:
os.makedirs(local_path)
print('{0} creat successful!'.format(local_path))
else:
pass
bufsize = 1024
self.cd(get_path)
filename_list = self.ls()
i = 1
for filename in filename_list:
try:
with open(local_path + filename, 'wb') as fp:
command_result = self.ftp.retrbinary(f'RETR {filename}', fp.write, bufsize)
print(command_result, f'下载成功,已成功下载数量:{i}')
i += 1
except Exception as e:
print(e)
# 关闭资源
def __del__(self):
self.ftp.quit()
# 之前有个小问题 现在修复掉了,另外代码缺陷,如果一个文件夹下的还有文件夹,这种情况会出现这个文件夹下的文件下的文件无法正常上传。目前解决思路,对文件夹下所有文件进行遍历,如果文件名没有出现'.'认为是一个文件夹,并进入该文件夹下(记录路径)。。。。 最后统一放入列表,遍历列表上传、。。。