My best friend's computer desktop is always messy, and I really can't stand it anymore. Use Python to realize one-click automatic classification and management of files.

My girlfriend's computer desktop looks like this.

It can only be said that fortunately it is a mac. Otherwise, the computer should be very stuck. Today I will also teach you how to sort out your opinions.

Different file extensions are classified into different categories

Let's first list roughly several types of files, and set them according to the suffix of the file, roughly as follows

 
 

SUBDIR = {
    "DOCUMENTS": [".pdf", ".docx", ".txt", ".html"],
    "AUDIO": [".m4a", ".m4b", ".mp3", ".mp4"],
    "IMAGES": [".jpg", ".jpeg", ".png", ".gif"],
    "DataFile": [".csv", ".xlsx"]
}

The file suffixes listed above are not comprehensive. Readers can add them according to their own needs, and classify them according to their preferences. Then we customize a function to judge whether it is based on an input file suffix. Which category does it belong to

 
 

def pickDir ( value ):
    for category , extent in SUBDIR . items ( ) :
        for suffix in extent :
            if suffix == value :
                return category

For example, if the input is .pdfreturned, it is DOCUMENTSthis class. We also need to customize a function to traverse all the files in the current directory, obtain the suffixes of many files, and move these files with different suffixes into folders of different categories. The code is as follows

 
 

def organizeDir(path_val):

    for item in os.scandir(path_val):
        if item.is_dir():
            continue

        filePath = Path(item)
        file_suffix = filePath.suffix.lower()
        directory = pickDir(file_suffix)
        directoryPath = Path(directory )
        # Create a new folder, if the folder does not exist
        if directoryPath.is_dir() != True:
            directoryPath.mkdir()
        filePath.rename(directoryPath.joinpath(filePath))

output

PythonLet's build on the basis again, and then encapsulate it 可视化GUI界面. The code is as follows

 
 

class FileOrgnizer(QWidget):
    def __init__(self):
        super().__init__()
        self.lb = QLabel(self)
        self.lb.setGeometry(70, 25, 80, 40)
        self.lb.setText('文件夹整理助手:')
        self.textbox = QLineEdit(self)
        self.textbox.setGeometry(170, 30, 130, 30)
        self.findButton = QPushButton('整理', self)
        self.findButton.setGeometry(60, 85, 100, 40)
        self.quitButton = QPushButton('退出', self)
        self.quitButton.clicked.connect(self.closeEvent)
        self.findButton.clicked.connect(self.organizeDir)
        self.quitButton.setGeometry(190, 85, 100, 40)
        self.setGeometry(500, 500, 350, 150)
        self.setWindowTitle('Icon')
        self.setWindowIcon(QIcon('../751.png'))
        self.show()

    def pickDir(self, value):
        for category, ekstensi in SUBDIR.items():
            for suffix in ekstensi:
                if suffix == value:
                    return category

    def organizeDir(self, event):

        path_val = self.textbox.text()
        print("路径为: " + path_val)
        for item in os.scandir(path_val):
            if item.is_dir():
                continue

            filePath = Path(item)
            fileType = filePath.suffix.lower()
            directory = self.pickDir(fileType)
            if directory == None:
                continue

            directoryPath = Path(directory)
            if directoryPath.is_dir() != True:
                directoryPath.mkdir()
            filePath.rename(directoryPath.joinpath(filePath))
        reply = QMessageBox.information(self, "Done" , "The task is completed, do you want to exit?", QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
        if reply == QMessageBox.Yes:
            event.accept()
        else:
            event.ignore()

    def closeEvent(self, event ):
        reply = QMessageBox.question(self, 'Exit',
                                     "Are you sure to exit?", QMessageBox.Yes |
                                     QMessageBox.No, QMessageBox.No)
        if reply == QMessageBox.Yes:
            event.accept()
        else:
            event.ignore()

Results as shown below

Finally, we package the code into an executable file through pyinstallerthe module , and the operation instructions are as followsPython

pyinstaller -F -w 文件名.py

The meanings of some parameters are as follows:

  • -F: means to generate a single executable file

  • -w: Indicates to remove the console window, which is GUIvery useful in the interface

  • -i: Icon representing an executable file

 Pay attention to the public account: Python Gu Muzi to receive the complete code

Guess you like

Origin blog.csdn.net/TZ45678/article/details/124781190