python实现带gui的ftp软件_Python GUI开发之FTP客户端续

这一篇博客是继上一篇博客,想了解的可以直走右拐。

上一篇主要讲了客户端的界面,这一篇主要讲解FTP客户端的两个功能,文件下载,以及压缩下载。

文件下载

调用处

self.downbt = Button(self.right, text='下载', command=self.download)

定义download函数

def download(self):

self.getrootpath()

check = self.list.get(self.list.curselection())

self.dpath = []

self.downloadfiles(check, self.rootpath)

self.f.cwd('/'.join(self.path))

self.getrootpath来获取下载的存放路径,具体获取代码如下:

def getrootpath(self):

self.rootpath = os.path.join(os.path.curdir, 'download')

if not os.path.exists(self.rootpath):

os.mkdir(self.rootpath)

直接在当前目录下创建download文件夹,用来存放下载的文件。

check = self.list.get(self.list.curselection())用来获取选中的目录或文件。

self.dpath用来存储下载的目录的深度,主要为了下载的时候能够准确定位当前下载的准确位置

self.downloadfiles(check, self.rootpath),具体的下载代码

def downloadfiles(self,dirs,rootpath):

if dirs:

try:

self.f.cwd(dirs)

self.dpath.append(dirs)

newdir = os.path.join(rootpath,'/'.join(self.dpath))

if not os.path.exists(newdir):

os.mkdir(newdir)

for dir in self.f.nlst():

self.downloadfiles(dir,rootpath)

self.dpath.pop()

nowpath = '/'.join(self.path)+'/'+'/'.join(self.dpath)

self.f.cwd(nowpath)

except ftplib.error_perm:

newfile = os.path.join(rootpath,'/'.join(self.dpath)+'/'+dirs)

with open(newfile,'wb') as f:

self.f.retrbinary('RETR %s' % (dirs), f.write)

下载代码也是很简单,进入到该目录(cwd),这个时候如果是文件夹,就不会发生异常,如果不是文件夹,那么就可以认定是文件了

i. 先假定是文件夹,那么记录目录深度(self.dpath.append(dirs)),并在本地创建目录,然后递归调用下载代码,遍历该目录下的所有文件。这一层文件遍历完了之后,更新目录深度(self.dpath.pop()),这个时候需要ftp也要同时更新其所在目录,self.path在上一个博客已经说明,其代表用户进入目录,这里可以看做是用户最后一次点击进行下载的那个目录,加上下载的目录深度,也就是当前的目录了,举个例子

1. 用户在‘home/user’点击,那么我们的self.path记录的是['home','user']

2. 然后下载‘name/name1’中的文件,当前的dirs也就是name1,

这个时候我们的self.dpath记录的是['name','name1']

3. 当遍历完name1下的文件之后,我们需要pop self.dpath顶部的路径,

这个时候self.dpath存储的就是['name']

4. 最后我们所处的路径就是'home/user/name',也就是self.path和self.dpath的连结。

ii. 如果是文件的话,那么就会被异常捕获,这个时候只需要通过retrbinary,将ftp的文件以二进制的形式写入到本地即可。

5.远程跳转到选择的文件位置即可

压缩下载

调用处

self.ziplist = Button(self.right, text='备份', command=self.zipdownload)

定义zipdownload函数

def zipdownload(self):

self.getrootpath()

check = self.list.get(self.list.curselection())

rootpath = os.path.join(self.rootpath, 'temp')

if not os.path.exists(rootpath):

os.mkdir(rootpath)

self.dpath = []

self.downloadfiles(check, rootpath)

zipname = os.listdir(rootpath)[0]

temppath = os.path.join(rootpath, zipname)

z = zipfile.ZipFile(os.path.join(self.rootpath, zipname + '.zip'), 'w', zipfile.ZIP_DEFLATED)

for dirpath, dirnames, filenames in os.walk(temppath):

for file in filenames:

z.write(os.path.join(dirpath, file))

z.close()

self.rmtemp(rootpath)

self.f.cwd('/'.join(self.path))

创建temp文件夹用来临时存放下载文件

zipname = os.listdir(rootpath)[0] 获取下载文件夹的名字,后面压缩的文件名即这个名字

创建压缩包,通过zipfile.ZipFile进行创建,然后遍历temp中的文件,os.walk会找到目录下的所有文件,将每个文件写入到压缩文件中即可

删除temp临时目录

def rmtemp(self,temppath):

for root, dirs, files in os.walk(temppath, topdown=False):

for name in files:

os.remove(os.path.join(root, name))

for name in dirs:

os.rmdir(os.path.join(root, name))

os.rmdir(temppath)

通过os.walk遍历temp临时文件夹,files中存放的是文件,dirs存放的是文件夹,先删除文件,可以避免删除文件夹失败,最后删除该临时文件夹,就完成了删除。

5.远程跳转到选择的文件位置即可

上述过程是否看懂了呢,FTP客户端就先到这里了。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
PyQt5是一个Python绑定的Qt库,可以用来创建GUI应用程序。要实现FTP服务器与客户端文件上传和下载功能,你可以使用Python内置的ftplib库来处理FTP操作。 首先,你需要创建一个FTP服务器。可以使用Pythonftplib库来实现这一点。下面是一个简单的例子: ```python from ftplib import FTP def start_ftp_server(): ftp = FTP() ftp.set_pasv(True) ftp.bind(("localhost", 21)) ftp.listen(5) while True: conn, addr = ftp.accept() print("Connected by", addr) conn.send("220 Welcome to the FTP server\r\n") while True: command = conn.recv(1024).decode().strip() if command == "QUIT": conn.send("221 Goodbye\r\n") conn.close() break elif command.startswith("STOR"): filename = command.split(" ")[1] conn.send("150 Ok to send data\r\n") with open(filename, "wb") as file: while True: data = conn.recv(1024) if not data: break file.write(data) conn.send("226 Transfer complete\r\n") elif command.startswith("RETR"): filename = command.split(" ")[1] try: file = open(filename, "rb") conn.send("150 Ok to send data\r\n") data = file.read(1024) while data: conn.send(data) data = file.read(1024) file.close() conn.send("226 Transfer complete\r\n") except FileNotFoundError: conn.send("550 File not found\r\n") else: conn.send("500 Unknown command\r\n") start_ftp_server() ``` 上述代码创建了一个简单的FTP服务器,监听本地地址的21端口。它支持QUIT、STOR和RETR命令。QUIT命令用于断开连接,STOR命令用于上传文件,RETR命令用于下载文件。 接下来,你可以使用PyQt5创建一个FTP客户端GUI应用程序。下面是一个示例: ```python import sys from PyQt5.QtWidgets import QApplication, QMainWindow, QFileDialog, QMessageBox from PyQt5.uic import loadUi from ftplib import FTP class FTPClient(QMainWindow): def __init__(self): super(FTPClient, self).__init__() loadUi("ftp_client.ui", self) # 使用Qt Designer设计的UI文件 self.connectButton.clicked.connect(self.connect_to_server) self.uploadButton.clicked.connect(self.upload_file) self.downloadButton.clicked.connect(self.download_file) self.ftp = FTP() def connect_to_server(self): host = self.hostLineEdit.text() port = int(self.portLineEdit.text()) username = self.usernameLineEdit.text() password = self.passwordLineEdit.text() try: self.ftp.connect(host, port) self.ftp.login(username, password) self.statusbar.showMessage("Connected to FTP server") except Exception as e: self.statusbar.showMessage("Failed to connect: " + str(e)) def upload_file(self): file_path, _ = QFileDialog.getOpenFileName(self, "Select file to upload") if file_path: try: with open(file_path, "rb") as file: self.ftp.storbinary("STOR " + file_path, file) self.statusbar.showMessage("File uploaded successfully") except Exception as e: self.statusbar.showMessage("Failed to upload file: " + str(e)) def download_file(self): file_path, _ = QFileDialog.getSaveFileName(self, "Save file as") if file_path: try: with open(file_path, "wb") as file: self.ftp.retrbinary("RETR " + file_path, file.write) self.statusbar.showMessage("File downloaded successfully") except Exception as e: self.statusbar.showMessage("Failed to download file: " + str(e)) if __name__ == "__main__": app = QApplication(sys.argv) window = FTPClient() window.show() sys.exit(app.exec_()) ``` 上述代码使用PyQt5创建了一个简单的FTP客户端应用程序。它连接到指定的FTP服务器,并提供了上传和下载文件的功能。 你需要使用Qt Designer设计一个UI界面,并保存为ftp_client.ui文件。然后,使用`loadUi`函数加载UI文件。 这只是一个简单的示例,你可以根据自己的需求进行修改和扩展。希望对你有所帮助!

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值