Python Extra: Use the module os+shutil to organize computer files with one click

Hello, everyone, my name is wangzirui32, today we will learn how to use the os+shutil module to organize computer files with one click.
Start learning!

Preface

Recently, a folder on my computer is very "chaotic", so I decided to write a small Python program to organize billions of files.
This is my messy folder:
folder
Okay, let’s start coding!

1. Write auxiliary module module

First, we have to write an auxiliary finishing module, open a Python file and name it module.py.

1.1 Directory class

Open module.py and enter:

# 导入所需的模块
import os
import shutil

# 定义Directory类
class Directory():
    def __init__(self, directory_name, file_suffix):
    	# 参数:文件夹名 文件后缀名
        self.file_suffix = file_suffix
        self.directory_name = directory_name
        # 要保存的文件
        self.file_list = []

    def add_file(self, file_name):
    	# 获取文件后缀名 并判断是否在file_suffix列表中
        if file_name.split('.')[-1] in self.file_suffix:
        	# 如果有 则添加到file_list
            self.file_list.append(file_name)
            return True
        else:
            return False
            
	def save_files(self):
		# 这个方法用于保存已经添加的文件
		# 首先使用mkdir函数创建文件夹
        os.mkdir(path + "\\" + self.directory_name)
        for file in self.file_list:
        	# 再使用move函数一个一个移动文件
            shutil.move(path + "\\" + file, path + "\\" + self.directory_name)

The Directory class is defined to facilitate the unified management of files. First, get the actual parameters: the name of the folder to be saved, and the file suffix (as a list). File suffix name This parameter is to determine which files with the suffix name meet the requirements to save.

add_file(fille_name) passes in a file name, and judges whether to store it according to the suffix name of this file. If it meets the conditions, add it to the storage list and return True, otherwise return False.

save_files() is used to save the files added to the file_list. First, automatically create a folder named as the attribute directory_name of this class, then traverse the file_list and use the shutil.move function to move the files to the created folder.

1.2 Directories

For more convenient management, I added the Directory class to module.py to facilitate the management of each Directory class:

class Directories():
    def __init__(self, *directories):
    	# 传入需要管理的Directory类 参数数量无限制
        self.directories = directories

	# 传入文件名
    def add_file(self, file_name):
        for directory in self.directories:
        	# 挨个执行Directory类中的add_file函数
        	# 直至符合存储条件
            if directory.add_file(file_name):
                break
	# 遍历每个Directory类
	# 并且执行Directory类的save_files函数保存
    def save_files(self):
        for directory in self.directories:
            directory.save_files()

2. Write the main project file demo.py

First, we determine which Directory classes to define. I defined 5 variables in demo.py according to the suffix of the file in the folder:

# 导入
import os
from module import Directory, Directories

# 先把路径设置为你需要整理的文件夹的路径
path = r"C:\Python\Python整理文件\我的文件夹"

# Tips:这里后缀名只写了一个,你还可以根据需要添加多个,如图片文件['png', 'jpg']等
pic = Directory("图片", ['png'])
word = Directory("word文档", ['doc'])
xls = Directory('表格文件', ['xls'])
csv = Directory("csv文件", ['csv'])
txt = Directory("文本文件", ['txt'])

Then we get all the file names in the folder:

files_name = os.listdir(path)

Then define a managed Directory class, and pass in all the Directory classes and paths that need to be managed:

directories = Directories(pic, word, xls, csv, txt)

Finally, use a for loop to traverse the file name and call the add_file function of the Directories class:

for file_name in files_name:
    directories.add_file(file_name)

At the end of the program, save:

directories.save_files()

Complete code:

# 注意:module模块需要编写
import os
from module import Directory, Directories

path = r"C:\Python\Python整理文件\我的文件夹"

files_name = os.listdir(path)

pic = Directory("图片", ['png'])
word = Directory("word文档", ['doc'])
xls = Directory('表格文件', ['xls'])
csv = Directory("csv文件", ['csv'])
txt = Directory("文本文件", ['txt'])

directories = Directories(pic, word, xls, csv, txt)

for file_name in files_name:
    directories.add_file(file_name)
directories.save_files()

3. Show the results

Run the code, my folder is organized like this:
After finishing

Write at the end

Here to explain, writing so complicated is to facilitate the modification of the program, if I want to classify the PDF file, I can directly add it to the code of demo.py:

# 省去一些代码
csv = Directory("csv文件", ['csv'])
# 在csv后面添加新的代码
pdf = Directory("PDF文件", ['pdf'])

Then, modify the parameters passed in to Directories:

directories = Directories(pic, word, xls, csv, txt, pdf) # 新加入pdf

This can add the function of categorized PDF to the program. Is it very light and easy to modify?


Alright, today’s class is over, if you like, please give me a thumbs up and follow me, bye bye!

Guess you like

Origin blog.csdn.net/wangzirui32/article/details/113881614