


I wrote a small tool in Python to help you organize even complex folders in minutes!
Too bad
I admit that I am not a person who likes to tidy up my desktop, because I think a messy desktop makes it easier to find files.
Haha, but the desktop has been so messy recently that I can’t even see it anymore. It almost takes up the entire screen. Although there are many software to organize the desktop with one click, I also need to organize files in other paths, so I thought of using Python to complete this requirement.
Effect display
I divided the files into 9 major categories, namely pictures, videos, audios, documents, compressed files, and common formats , program scripts, executable programs and font files.
# 不同文件组成的嵌套字典 file_dict = { '图片': ['jpg','png','gif','webp'], '视频': ['rmvb','mp4','avi','mkv','flv'], "音频": ['cd','wave','aiff','mpeg','mp3','mpeg-4'], '文档': ['xls','xlsx','csv','doc','docx','ppt','pptx','pdf','txt'], '压缩文件': ['7z','ace','bz','jar','rar','tar','zip','gz'], '常用格式': ['json','xml','md','ximd'], '程序脚本': ['py','java','html','sql','r','css','cpp','c','sas','js','go'], '可执行程序': ['exe','bat','lnk','sys','com'], '字体文件': ['eot','otf','fon','font','ttf','ttc','woff','woff2'] }
file_dict is a dictionary defined by ourselves, which contains formats commonly used in our study and work. The commonly used formats need to be explained to everyone. For files that are often used but don’t know which category to put them in, they are stored here.
Note: If your computer has more file formats, you only need to modify the above file_dict dictionary.
Development Ideas
Developing such a small tool involves a total of three Python libraries, namely the os module, shutil module, and glob module. They are used together to process files and folders. , simply awesome!
The general idea of the entire development steps is as follows:
- ① Given a file path arbitrarily;
- ② Get all the files under the current file path, and Get the suffix corresponding to each file;
- ③ Determine whether each file is in the specified nested dictionary, and return the corresponding file classification;
- ④ Determine the file of each file classification Whether the folder exists. Because it is necessary to create a new folder to store files in categories;
- ⑤ Copy each file to the corresponding category;
The complete code is as follows: [Attached is the detailed code Remarks]
# 导入相关库 import os import glob import shutil # 采用input()函数,动态输入要处理的文件路径。 path = input("请输入要清理的文件路径:") # 定义一个文件字典,不同的文件类型,属于不同的文件夹,一共9个大类。 file_dict = { '图片': ['jpg','png','gif','webp'], '视频': ['rmvb','mp4','avi','mkv','flv'], "音频": ['cd','wave','aiff','mpeg','mp3','mpeg-4'], '文档': ['xls','xlsx','csv','doc','docx','ppt','pptx','pdf','txt'], '压缩文件': ['7z','ace','bz','jar','rar','tar','zip','gz'], '常用格式': ['json','xml','md','ximd'], '程序脚本': ['py','java','html','sql','r','css','cpp','c','sas','js','go'], '可执行程序': ['exe','bat','lnk','sys','com'], '字体文件': ['eot','otf','fon','font','ttf','ttc','woff','woff2'] } # 定义一个函数,传入每个文件对应的后缀。判断文件是否存在于字典file_dict中; # 如果存在,返回对应的文件夹名;如果不存在,将该文件夹命名为"未知分类"; def func(suffix): for name, type_list in file_dict.items(): if suffix.lower() in type_list: return name return "未知分类" # 递归获取 "待处理文件路径" 下的所有文件和文件夹。 for file in glob.glob(f"{path}/**/*",recursive=True): # 由于我们是对文件分类,这里需要挑选出文件来。 if os.path.isfile(file): # 由于isfile()函数,获取的是每个文件的全路径。这里再调用basename()函数,直接获取文件名; file_name = os.path.basename(file) suffix = file_name.split(".")[-1] # 判断 "文件名" 是否在字典中。 name = func(suffix) #print(func(suffix)) # 根据每个文件分类,创建各自对应的文件夹。 if not os.path.exists(f"{path}\{name}"): os.mkdir(f"{path}\{name}") # 将文件复制到各自对应的文件夹中。 shutil.copy(file,f"{path}\{name}")
The results are as follows:
Outlook
Huang has shared the code of this article with everyone. But I didn't make a visual interface for this code. At the same time, I also hope that everyone can package the program and send it directly to others so that they can use it directly.
The above is the detailed content of I wrote a small tool in Python to help you organize even complex folders in minutes!. For more information, please follow other related articles on the PHP Chinese website!

TomergelistsinPython,youcanusethe operator,extendmethod,listcomprehension,oritertools.chain,eachwithspecificadvantages:1)The operatorissimplebutlessefficientforlargelists;2)extendismemory-efficientbutmodifiestheoriginallist;3)listcomprehensionoffersf

In Python 3, two lists can be connected through a variety of methods: 1) Use operator, which is suitable for small lists, but is inefficient for large lists; 2) Use extend method, which is suitable for large lists, with high memory efficiency, but will modify the original list; 3) Use * operator, which is suitable for merging multiple lists, without modifying the original list; 4) Use itertools.chain, which is suitable for large data sets, with high memory efficiency.

Using the join() method is the most efficient way to connect strings from lists in Python. 1) Use the join() method to be efficient and easy to read. 2) The cycle uses operators inefficiently for large lists. 3) The combination of list comprehension and join() is suitable for scenarios that require conversion. 4) The reduce() method is suitable for other types of reductions, but is inefficient for string concatenation. The complete sentence ends.

PythonexecutionistheprocessoftransformingPythoncodeintoexecutableinstructions.1)Theinterpreterreadsthecode,convertingitintobytecode,whichthePythonVirtualMachine(PVM)executes.2)TheGlobalInterpreterLock(GIL)managesthreadexecution,potentiallylimitingmul

Key features of Python include: 1. The syntax is concise and easy to understand, suitable for beginners; 2. Dynamic type system, improving development speed; 3. Rich standard library, supporting multiple tasks; 4. Strong community and ecosystem, providing extensive support; 5. Interpretation, suitable for scripting and rapid prototyping; 6. Multi-paradigm support, suitable for various programming styles.

Python is an interpreted language, but it also includes the compilation process. 1) Python code is first compiled into bytecode. 2) Bytecode is interpreted and executed by Python virtual machine. 3) This hybrid mechanism makes Python both flexible and efficient, but not as fast as a fully compiled language.

Useaforloopwheniteratingoverasequenceorforaspecificnumberoftimes;useawhileloopwhencontinuinguntilaconditionismet.Forloopsareidealforknownsequences,whilewhileloopssuitsituationswithundeterminediterations.

Pythonloopscanleadtoerrorslikeinfiniteloops,modifyinglistsduringiteration,off-by-oneerrors,zero-indexingissues,andnestedloopinefficiencies.Toavoidthese:1)Use'i


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

SublimeText3 Chinese version
Chinese version, very easy to use
