Small knowledge, big challenge! This paper is participating in theEssentials for programmers”Creative activities.
One, foreword
For people with obsessive-compulsive disorder, empty folders are not allowed to exist, and there are many files in the computer, and empty folders are not easy to find, it is really too troublesome to delete one by one, today I will share with you the operation of deleting empty folders. The article is verbose, so the reader can skip straight to the last paragraph.
Python OS module
In Python’s OS module, which encapsulates operations on files and paths, it only takes a few lines of code to traverse a file and delete an empty folder. So let’s look at some of the operations that we’re going to use.
1. View the files in the directory
The OS provides a listdir function to view files and folders in a directory, using the following functions:
import os
# list the files/folders in the current directory
file_list = os.listdir(".")
Output a list of returned files/folders
print(file_list)
Copy the code
The following output is displayed:
['.idea'.'dataset'.'main.py'.'nn'.'test'.'test.py'.'venv']
Copy the code
As you can see, the resulting list contains the names of the files and folders in the current directory.
2. Splicing paths
For safe and accurate access to our files, I recommend using the absolute path. Os. listdir generates a list of absolute paths to the file as follows:
import os
Get the absolute path to the current directory
abs_path = os.path.abspath(".")
The absolute path to install the file
file_list = []
# loop stitching
for file in os.listdir(abs_path):
file_list.append(abs_path + "\ \" + file)
print(file_list)
Copy the code
The following output is displayed:
['D:\\Coding Files\\Workplace\\PythonWorkplace\\Deep Learning\\.idea'.'D:\\Coding Files\\Workplace\\PythonWorkplace\\Deep Learning\\dataset']
Copy the code
We can also use list derivations to simplify the above code:
import os
abs_path = os.path.abspath(".")
file_list = [abs_path + "\ \" + i for i in os.listdir(abs_path)]
Copy the code
Instead of joining “\\” directly, we can use os.path.join as follows:
import os
path = os.path.join('test'.'test.py')
Test \test.py
Copy the code
The join function automatically ADAPTS slashes to different systems. Let’s change the above code to use join:
import os
abs_path = os.path.abspath(".")
file_list = [os.path.join(abs_path, i) for i in os.listdir('. ')]
print(file_list)
Copy the code
So we are done with the stitching of paths.
3, determine whether it is a file or folder
There are also ready-made functions:
import os
abs_path = os.path.abspath(".")
file_list = [os.path.join(abs_path, i) for i in os.listdir('. ')]
for file in file_list:
Check if it is a folder
if os.path.isdir(file):
print(file, "Yes folder")
Check if it is a file
elif os.path.isfile(file):
print(file, "Yes.")
Copy the code
Here are the two main functions:
os.path.isdir(file)
os.path.isfile(file)
Copy the code
In addition, we can check whether the directory is empty, which is special:
if not os.listdir("test") :print("Test directory is empty")
Copy the code
Here we see if it returns a sublist, if not an indication that there are no subfiles in the directory and therefore are empty.
4. Delete files
Here we need to use our os.rmdir function, here we need to pass the directory is empty directory to run properly, we can delete before checking whether empty directory:
if os.listdir("test"):
os.rmdir("test")
Copy the code
Delete empty folders in batches
Below we can combine the above content, to achieve a batch delete empty folder:
import os
abs_path = os.path.abspath(".")
file_list = [os.path.join(abs_path, i) for i in os.listdir('. ')]
for file in file_list:
if os.path.isdir(file) and not os.listdir(file):
os.rmdir(file)
print("Deleted", file)
Copy the code
The following output is displayed:
D:\Coding Files\Workplace\PythonWorkplace\Deep Learning\test11Copy the code
In this way, we can batch delete the empty folder under the specified directory. But what if we delete global empty folders? This is where the walk function is used:
import os
for root, dirs, files in os.walk(r"D:\\") :for file in files:
Get the file path
path = os.path.join(root, file)
if os.path.isdir(path) and not os.listdir(path):
os.rmdir(path)
print("Deleted:", path)
Copy the code
Above we have achieved the D disk so empty folder delete. The use of walk will be described in detail later.