当前位置:网站首页>S series · several postures for deleting folders
S series · several postures for deleting folders
2022-06-09 02:04:00 【The fate of the sleepers】
S series · Several poses for deleting folders
S Also known as water , It can also be read as Small, In the process of daily work and study , Occasionally I will find something I haven't seen before 、 Small 、 Interesting operation , Perhaps these operations are not meaningful for solving the current problems , Still want to record , Maybe you can write a complete article by yourself , Then write it down as a daily account .
Series article description :
S series ·<< Article title >>
platform :
windows 10.0
python 3.8
pywin32 227 ( Or install pypiwin32)
send2trash 1.5.0
Purpose
Delete a directory containing data files .
Delete pose
The following operations are in windows Operating in the system .
- Pose a
Right click the folder directly on the computer , Choose Delete , Or use Delete Press to delete the file , This method deletes files , Will transfer files to the recycle bin , If you need to recover , Click on Restore that will do .
- Position 2
stay python Used in os modular :
import os
delete_dir = r' Test folder '
for r, d, f in os.walk(delete_dir, topdown=False):
for files in f:
os.remove(os.path.join(r, files)) # Delete file
os.removedirs(r) # Delete folder , Must be empty
Use os.walk Traverse the contents of the file to be deleted , Default topdown=True, Output the outermost layer first and then the inner layer , The non empty folder will be output first , It's about using os.removedirs Deleting a non empty folder will try to report an error , take topdown=False, First, export and delete the inner files one by one , Finally, delete the upper folder , Until all are deleted .
- Pose three
pathlib modular :
from pathlib import Path
delete_dir = Path(r' Test folder ')
# Delete all files
[i.unlink() for i in delete_dir.rglob('*') if i.is_file()]
# Delete all empty folders contained
[i.rmdir() for i in delete_dir.rglob('*') if i.is_dir()]
# Delete the current folder
delete_dir.rmdir()
And os similar , Delete files and folders separately , Two recursions determine whether it is a file or directory , And delete according to the corresponding deletion method , Finally, delete the current folder .
- Position 4
shutil modular
from shutil import rmtree
delete_dir = r' Test folder '
rmtree(delete_dir)
rmtree Recursively return all files and folders in this directory , And delete it , The principle is the same as Position 2 , The following is a rmtree The core code part :


rmtree First, determine whether the deletion method is safe deletion , Take the safe deletion method as an example , Judge the recursive result , If it is a folder , Determine whether there are files in the inner layer , If you still have recursion , Then delete the recursive result , If it's a document , Delete directly , This way is compared to Position 2 With more judgment on file status .
- send2trash+shell
All of the above python Method to delete a file will be deleted directly , Will not go through the recycle bin , If you want to do something similar to pose one , Installable send2trash modular , Transfer files to the recycle bin .
pip install send2trash
pip install pywin32 ( perhaps pip install pypiwin32)
import send2trash
delete_dir = r' Test folder '
send2trash.send2trash(delete_dir)
win32com yes pywin32 A module in the package , call shell Methods to treat the recycle bin .
from win32com.shell import shell, shellcon
def recyclebin_empty(confirm=True, show_progress=True, sound=True):
flags = 0
if not confirm: # Prompt box
flags |= shellcon.SHERB_NOCONFIRMATION
if not show_progress: # Delete progress
flags |= shellcon.SHERB_NOPROGRESSUI
if not sound: # Complete the tone
flags |= shellcon.SHERB_NOSOUND
shell.SHEmptyRecycleBin(None, None, flags)
recyclebin_empty(False, False, False)
Define a function , By default, the prompt box for emptying the recycle bin will be displayed , Display progress and delete completion prompt tone . The combination of the two functions can realize Pose a Operation process .
summary
This article through several postures , Delete the files to be deleted , Pure sharing of personal insights , Deleting a file is basically done with your hands , Before using the computer, I accidentally had a draught , Use it directly shutil.rmtree To delete the occasional Caton , I thought this deletion method was very slow , So I searched the Internet , Then use pathlib Modules can be deleted quickly , Just when I wanted to share this , I restart the computer and run it again , Find out shutil.rmtree Can delete quickly , After several tests ,shutil.rmtree comparison pathlib Faster delete , Why the deletion took a long time is unknown .
Misty rain in this mountain , Only scholars and poets remain .
2022.6.8 leave
边栏推荐
猜你喜欢

Shell weather forecast

基于 Selenium 的 UESTC Daily Report 实现

Create house with UE4 brush BSP

Security analysis and demonstration of contract private data leakage
![[high level knowledge] epoll implementation principle of user mode protocol stack](/img/bc/f1d8ab69145ff5f644529e292dc5d5.png)
[high level knowledge] epoll implementation principle of user mode protocol stack

浮點數詳解(一篇徹底學通浮點數)
![[1037. effective boomerang]](/img/e2/ccac2e7df2db316da4e88bdc709e6e.png)
[1037. effective boomerang]

Senior learning long talk about programmers

How to use superset to seamlessly connect with MRS for self-service analysis

shell 天气预报
随机推荐
[Tianyi cup 2021]esay_ eval
Former Disney executive says Depp will return to pirates of the Caribbean to continue playing Captain
How to use superset to seamlessly connect with MRS for self-service analysis
Shell command output
双检锁为什么需要使用volatile关键字
[1037. effective boomerang]
C语言成绩记录簿
shell 比较大小
How Bi makes SaaS products have a "sense of security" and "sensitivity" (Part I)
Why the volatile keyword is required for double check locks
Swift GCD DispatchGroup Notify wait DispatchSourceTimer Monitor system file Two apps communicate
Suppress status error LNK1104 failed to open the file "boost_thread-vc142-mt-gd-x64-1\u 79.lib"
C语言学生选修课查询系统
Shell display system information menu
Jenkins can view the forgotten credential password based on the credential ID and how to reset the admin password
C language vaccine reservation management system
shell 命令输出
shell 颜色输出
基于 Selenium 的 UESTC Daily Report 实现
Mp4 structure