QT(四)文件操作

https://blog.csdn.net/humanking7/article/details/80546728 参考链接
https://www.cnblogs.com/wt7018/p/12057094.html shutil文件操作

写个小应用

1 app.py

from filedo import *
from filehandle import *
from PyQt5 import QtCore, QtWidgets,QtGui
from PyQt5.QtWidgets import QApplication,  QMainWindow, QMessageBox,QTableWidgetItem,QAbstractItemView,QFileDialog
from PyQt5.QtCore import Qt
import re
import sys

class App(Filedo,QMainWindow):

    def __init__(self):
        super(App,self).__init__()
        self.setupUi(self)
        self.openfile = './'
        self.fileobj = FileHandle()

        self.pushButton.clicked.connect(self.copyOnce)
        self.pushButton_2.clicked.connect(self.deleteOnce)
        self.pushButton_3.clicked.connect(self.cutOnce)
        self.pushButton_4.clicked.connect(self.tarOnce)

    def copyOnce(self):
        reply = QMessageBox.question(self, '文件', '复制文件还是文件夹?', QMessageBox.Yes | QMessageBox.No)
        if reply == QMessageBox.Yes:
            # 打开一个文件,返回文件名,./为默认打开路径,最后一个参数为过滤器符合正则
            filename = QFileDialog.getOpenFileName(self, "选择需要复制的文件", self.openfile, "all files(*)")[0]
        else:
            # 打开一个文件,返回文件名,./为默认打开路径,最后一个参数为过滤器符合正则
            filename = QFileDialog.getExistingDirectory(None, "选择需要复制的文件夹", self.openfile,"*")
        # .sapn返回时一个元素,2个元素,分别是起点和终点,目的是重新设置默认路径
        # self.openfile = filename[:re.search('.', filename).span()[0]]
        try:
            self.openfile = "/".join(filename.split("/")[:len(filename.split("/"))-1])
            copyname = QFileDialog.getExistingDirectory(self, "复制到这", self.openfile)
            self.fileobj.setPath(filename)
            if(self.fileobj.copyFile(os.path.join(copyname,filename.split("/")[-1]))):
                self.textEdit.append("将文件{0}复制到{1}".format(filename,os.path.join(copyname,filename.split("/")[-1])))
            else:
                self.textEdit.append("文件或文件夹不存在")
        except Exception as e:
            print(e)

    def deleteOnce(self):
        reply = QMessageBox.question(self, '文件', '删除文件还是文件夹?', QMessageBox.Yes | QMessageBox.No)
        if reply == QMessageBox.Yes:
            # 打开一个文件,返回文件名,./为默认打开路径,最后一个参数为过滤器符合正则
            filename = QFileDialog.getOpenFileName(self, "选择需要删除的文件", self.openfile, "all files(*)")[0]
        else:
            # 打开一个文件,返回文件名,./为默认打开路径,最后一个参数为过滤器符合正则
            filename = QFileDialog.getExistingDirectory(None, "选择需要删除的文件夹", self.openfile,"*")
        # .sapn返回时一个元素,2个元素,分别是起点和终点,目的是重新设置默认路径
        # self.openfile = filename[:re.search('.', filename).span()[0]]
        try:
            self.openfile = "/".join(filename.split("/")[:len(filename.split("/")) - 1])
            self.fileobj.setPath(filename)
            if (self.fileobj.deleteFile()):
                self.textEdit.append("将文件{0}删除".format(filename))
            else:
                self.textEdit.append("文件或文件夹不存在")
        except Exception as e:
            print(e)

    def cutOnce(self):
        reply = QMessageBox.question(self, '文件', ' 改名文件还是文件夹?', QMessageBox.Yes | QMessageBox.No)
        if reply == QMessageBox.Yes:
            # 打开一个文件,返回文件名,./为默认打开路径,最后一个参数为过滤器符合正则
            filename = QFileDialog.getOpenFileName(self, "选择需要改名的文件", self.openfile, "all files(*)")[0]
        else:
            # 打开一个文件,返回文件名,./为默认打开路径,最后一个参数为过滤器符合正则
            filename = QFileDialog.getExistingDirectory(None, "选择需要改名的文件夹", self.openfile,"*")
        # .sapn返回时一个元素,2个元素,分别是起点和终点,目的是重新设置默认路径
        # self.openfile = filename[:re.search('.', filename).span()[0]]
        try:
            self.openfile = "/".join(filename.split("/")[:len(filename.split("/")) - 1])
            self.fileobj.setPath(filename)
            self.fileobj.cutFile()
            self.textEdit.append("修改文件{0}".format(filename))
        except Exception as e:
            print(e)

    def tarOnce(self):
        # 打开一个文件,返回文件名,./为默认打开路径,最后一个参数为过滤器符合正则
        filename = QFileDialog.getExistingDirectory(None, "选择需要改名的文件夹", self.openfile)
        # .sapn返回时一个元素,2个元素,分别是起点和终点,目的是重新设置默认路径
        # self.openfile = filename[:re.search('.', filename).span()[0]]
        self.openfile = "/".join(filename.split("/")[:len(filename.split("/")) - 1])
        self.fileobj.setPath(filename)
        self.fileobj.tarFile()
        self.textEdit.append("压缩文件{0}".format(filename))

    def closeEvent(self, event):
        reply = QMessageBox.question(self, '确认', '确认退出吗?', QMessageBox.Yes | QMessageBox.No)
        if reply == QMessageBox.Yes:
            event.accept()
        else:
            event.ignore()

if(__name__=="__main__"):
    app = QApplication(sys.argv)
    fileapp = App()
    fileapp.show()
    sys.exit(app.exec_())

2 filehandle 定义类处理文件

import shutil
import os
from renamefile import *
from tarfile import *

# 操作文件用os,操作目录最好用shutil
class FileHandle(object):
    def __init__(self):
        self.path = "./"

    def setPath(self,path):
        self.path = path

    def copyFile(self,newpath):
        if(os.path.isdir(self.path) or os.path.isfile(self.path)):
            if (os.path.isdir(self.path)):
                # 左侧参数为源文件,右侧为copy后的新文件
                shutil.copytree(self.path, newpath)
            elif (os.path.isfile(self.path)):
                shutil.copy(self.path, newpath)
            return True
        else:
            return False

    def deleteFile(self):
        if(os.path.isdir(self.path) or os.path.isfile(self.path)):
            if (os.path.isdir(self.path)):
                shutil.rmtree(self.path)
            elif (os.path.isfile(self.path)):
                os.remove(self.path)

            return True
        else:
            return False

    def cutFile(self):
        self.renamefile = Rename()
        self.renamefile.filename = self.path
        self.renamefile.show()
        # shutil.move(self.path, newpath)

    def tarFile(self):
        self.tarfile = Tarfile(self.path)
        self.tarfile.show()

3 主窗口

# -*- coding: utf-8 -*-

# Form implementation generated from reading ui file 'filedo.ui'
#
# Created by: PyQt5 UI code generator 5.13.0
#
# WARNING! All changes made in this file will be lost!


from PyQt5 import QtCore, QtGui, QtWidgets


class Filedo(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(1029, 754)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.widget = QtWidgets.QWidget(self.centralwidget)
        self.widget.setGeometry(QtCore.QRect(0, 0, 1021, 721))
        self.widget.setStyleSheet("background-color:rgb(85, 170, 255)")
        self.widget.setObjectName("widget")
        self.textEdit = QtWidgets.QTextEdit(self.widget)
        self.textEdit.setGeometry(QtCore.QRect(10, 10, 1001, 321))
        self.textEdit.setStyleSheet("background-color:rgb(255, 255, 255)")
        self.textEdit.setObjectName("textEdit")
        self.label = QtWidgets.QLabel(self.widget)
        self.label.setGeometry(QtCore.QRect(10, 340, 1001, 41))
        self.label.setStyleSheet("background-color:qlineargradient(spread:pad, x1:0, y1:1, x2:0, y2:0, stop:0 rgba(0, 85, 255, 255), stop:1 rgba(255, 255, 255, 255));\n"
"font: 75 18pt \"Aharoni\";color:#fff")
        self.label.setAlignment(QtCore.Qt.AlignCenter)
        self.label.setObjectName("label")
        self.pushButton = QtWidgets.QPushButton(self.widget)
        self.pushButton.setGeometry(QtCore.QRect(100, 440, 81, 31))
        self.pushButton.setStyleSheet("background-color:rgb(255, 255, 255)")
        self.pushButton.setObjectName("pushButton")
        self.pushButton_2 = QtWidgets.QPushButton(self.widget)
        self.pushButton_2.setGeometry(QtCore.QRect(100, 520, 81, 31))
        self.pushButton_2.setStyleSheet("background-color:rgb(255, 255, 255)")
        self.pushButton_2.setObjectName("pushButton_2")
        self.pushButton_3 = QtWidgets.QPushButton(self.widget)
        self.pushButton_3.setGeometry(QtCore.QRect(280, 440, 81, 31))
        self.pushButton_3.setStyleSheet("background-color:rgb(255, 255, 255)")
        self.pushButton_3.setObjectName("pushButton_3")
        self.pushButton_4 = QtWidgets.QPushButton(self.widget)
        self.pushButton_4.setGeometry(QtCore.QRect(280, 520, 81, 31))
        self.pushButton_4.setStyleSheet("background-color:rgb(255, 255, 255)")
        self.pushButton_4.setObjectName("pushButton_4")
        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtWidgets.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 1029, 23))
        self.menubar.setObjectName("menubar")
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
        self.label.setText(_translate("MainWindow", "操作"))
        self.pushButton.setText(_translate("MainWindow", "复制"))
        self.pushButton_2.setText(_translate("MainWindow", "删除"))
        self.pushButton_3.setText(_translate("MainWindow", "重命名"))
        self.pushButton_4.setText(_translate("MainWindow", "压缩"))

4 重命名窗口

# -*- coding: utf-8 -*-

# Form implementation generated from reading ui file 'renamefile.ui'
#
# Created by: PyQt5 UI code generator 5.13.0
#
# WARNING! All changes made in this file will be lost!


from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import QApplication,  QMainWindow, QMessageBox,QTableWidgetItem,QAbstractItemView,QFileDialog
import os
import shutil

class Rename(QMainWindow):
    def __init__(self):
        super(Rename,self).__init__()
        self.setupUi(self)
        self.pushButton.clicked.connect(self.applyData)
        self.content = ""

    def applyData(self):
        try:
            path = "/".join(self.filename.split("/")[:len(self.filename.split("/")) - 1])
            print(os.path.join(path, "/"+self.lineEdit.text()))
            shutil.move(self.filename,os.path.join(path,  "/"+self.lineEdit.text()))
            self.content = "将{0}改名为{1}".format(self.filename,os.path.join(path, self.lineEdit.text()))
            self.hide()
        except Exception as e:
            print(e)

    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(323, 152)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.lineEdit = QtWidgets.QLineEdit(self.centralwidget)
        self.lineEdit.setGeometry(QtCore.QRect(140, 40, 113, 41))
        self.lineEdit.setObjectName("lineEdit")
        self.label = QtWidgets.QLabel(self.centralwidget)
        self.label.setGeometry(QtCore.QRect(50, 50, 91, 20))
        self.label.setObjectName("label")
        self.pushButton = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton.setGeometry(QtCore.QRect(120, 90, 81, 41))
        self.pushButton.setObjectName("pushButton")
        MainWindow.setCentralWidget(self.centralwidget)
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "修改文件名"))
        self.label.setText(_translate("MainWindow", "修改的文件名:"))
        self.pushButton.setText(_translate("MainWindow", "修改"))

5 压缩窗口

# -*- coding: utf-8 -*-

# Form implementation generated from reading ui file 'tarfile.ui'
#
# Created by: PyQt5 UI code generator 5.13.0
#
# WARNING! All changes made in this file will be lost!

from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import QApplication,  QMainWindow, QMessageBox,QTableWidgetItem,QAbstractItemView,QFileDialog
import os
import shutil
import re

class Tarfile(QMainWindow):
    def __init__(self,filename):
        try:
            super(Tarfile,self).__init__()
            self.setupUi(self)
            self.filename = filename
            self.filepath = './'
            self.pushButton.clicked.connect(self.tarHandle)
            self.pushButton_2.clicked.connect(self.saveFile)
            self.lineEdit.setText(filename)
        except Exception as e:
            print(e)

    def saveFile(self):
        try:
            name = self.filename.split("/")[-1]
            # 参数1,压缩后的路径与名字,参数2,格式,参数3 压缩对象
            shutil.make_archive(os.path.join(self.filepath,name), "zip", root_dir=self.filename)
            self.hide()
        except Exception as e:
            print(e)

    def tarHandle(self):
        try:
            # 打开一个文件,返回文件名,./为默认打开路径,最后一个参数为过滤器符合正则
            self.filepath = QFileDialog.getExistingDirectory(None, "选择文件夹", "./")

        except Exception as e:
            print(e)

    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(252, 158)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.pushButton = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton.setGeometry(QtCore.QRect(50, 20, 81, 41))
        self.pushButton.setObjectName("pushButton")
        self.pushButton_2 = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton_2.setGeometry(QtCore.QRect(150, 20, 81, 41))
        self.pushButton_2.setObjectName("pushButton")
        self.label = QtWidgets.QLabel(self.centralwidget)
        self.label.setGeometry(QtCore.QRect(20, 90, 91, 20))
        self.label.setObjectName("label")
        self.lineEdit = QtWidgets.QLineEdit(self.centralwidget)
        self.lineEdit.setGeometry(QtCore.QRect(90, 80, 121, 41))
        self.lineEdit.setObjectName("lineEdit")
        MainWindow.setCentralWidget(self.centralwidget)
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
        self.pushButton.setText(_translate("MainWindow", "另存为"))
        self.label.setText(_translate("MainWindow", "原路径:"))
        self.pushButton_2.setText(_translate("MainWindow", "确定"))

效果图:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值