Delete Files & Directories Using Python
Sahil
Posted on October 31, 2022
So far, we have learned many basic concepts of Python. We learned about:
- Data types & Variables
- String Manipulation Methods
- List & Dictionary Manipulation Methods
- Conditional Statements
- Loops
- File Handling
But now what?
We can not be good at something just by reading blogs or watching YouTube tutorials. We have to practice and keep practicing until we become good at it. So, in this blog, I will try to show most of the concepts we have learned so far.
โFor the things we have to learn before we can do them, we learn by doing them.โ
โ Aristotle
So, what we are gonna do?
Planning
In this blog, I will show you
- How can we list all the files and directories of a specific location using the os module
- Separate files and directories, and add them to their respective lists using the isfile() method
- Go through these lists of files and directories using for loop
- Delete files using the os module
- Delete directories using the shutil module
Apart from these, we will see a bit about error handling in Python as well. Even if we test our code, in a real-world environment, unexpected errors can or will arise eventually. To tackle these scenarios we use error handling. Error handling is a general programming concept it is not a Python-only concept.
Coding
Before we get into the code, I would like to mention that if you don't understand any line or have any doubt, you can always reach out to me on Twitter or LinkedIn. I will explain the code in little chunks and I will also add the whole code file at the end of this blog. We will proceed with:
1. Import necessary modules
import os
import shutil
2. Get the list of all files and directories of a specific location
# location of temp files in windows
location = 'C:\\Windows\\Temp'
file_dir = os.listdir(location)
Note: Mac people, you can use any temporary folder or directory you wish program won't stop working. I am a Windows user so don't know where temp files are stored on a Mac devices.
3. Separation of Files and Directories
The listdir() method returns files and directories both. So, we need to separate files and directories from file_dir.
only_files = []
only_dir = []
for i in file_dir:
# generate full path
full_path = os.path.join(location, I)
# checks if the given path is of file or not
if os.path.isfile(full_path):
only_files.append(full_path)
# checks if the given path is of directory or not
if os.path.isdir(full_path):
only_dir.append(os.path.join(full_path)
4. Delete files
# loop through the list that contains only files
for i in only_files:
try:
# os.chmod(i, 0o777)
os.remove(i) # removes the files
except Exception as e:
print(e)
Here, we have kept the whole delete logic (one line ๐) into the try and except
block. Why do we do this? It is possible that the file has been moved or we do not have access to the file. This situation can raise the error/exception and our code will stop working. There can be many ways to handle exceptions. But, I have selected the simple and easy path by just printing the error message. Don't worry we will learn about exception handling in the next blog.
5. Delete directories
# loop through the list that contains only directories
for i in only_dir:
try:
# os.chmod(i, 0o777)
shutil.rmtree(i, ignore_errors = False) # removes the the directory and all the sub-files and sub-directory that it might have
except Exception as e:
print(e)
The shutil.rmtree()
method will take input and will try to delete the directory and all its sub-files and directories. Here, we want to raise exceptions when the method fails to remove some files/directories. So, we passed the ignore_errors parameter with false as a value.
Note: In Windows, sometimes you will face permission issues. To avoid those, open your editor or console wherever you are trying to run this code as an administrator. For mac, uncomment os.chmod(i, 0o777) part. It should work but not sure because I have not tried it in the mac system.
This demo is just to understand the concepts better that we have learned so far. We can optimize code by deleting files/directories at the same time we are splitting them into two lists. But again this is to make you understand how to use python.
6. Convert whole logic into a function
Re-usability is very important in the programming world. It is not necessary for this program but just to show you we will convert the whole logic into a function. And we will call this function only.
def delete_temp_file(locations):
for location in locations:
try:
# get list of all files and directories
file_dir = os.listdir(location)
only_files = []
only_dir = []
for i in file_dir:
# checks if the given path is of file or not
# print(location+'\\'+i)
# print(os.path.join(location, i))
full_path = os.path.join(location, i)
if os.path.isfile(full_path):
only_files.append(full_path)
# checks if the given path is of directory or not
if os.path.isdir(full_path):
only_dir.append(full_path)
except Exception as e:
print(e)
# loop through the list that contains only files
for i in only_files:
try:
# os.chmod(i, 0o777)
os.remove(i) # removes the files
except Exception as e:
print(getattr(e, 'message', repr(e)))
# loop through the list that contains only directories
for i in only_dir:
try:
# os.chmod(i, 0o777)
# removes the the directory and all the sub-files and sub-directory it has
shutil.rmtree(i, ignore_errors = False)
except Exception as e:
print(e)
Now, execution time! ๐
Final Touch & Execution
This is repetitive, but I have added the whole code so that you can see it in one flow. Before you run it edit the location list as per your desire. Then go to the location where you saved the codebase and run python file_name.py
. You can find whole codebase on my Gist
import shutil
import os
def delete_temp_file(locations):
for location in locations:
try:
# get list of all files and directories
file_dir = os.listdir(location)
only_files = []
only_dir = []
for i in file_dir:
# generate full path
full_path = os.path.join(location, i)
# checks if the given path is of file or not
if os.path.isfile(full_path):
only_files.append(full_path)
# checks if the given path is of directory or not
if os.path.isdir(full_path):
only_dir.append(full_path)
except Exception as e:
print(e)
# loop through the list that contains only files
for i in only_files:
try:
# os.chmod(i, 0o777)
os.remove(i) # removes the files
except Exception as e:
print(getattr(e, 'message', repr(e)))
# loop through the list that contains only directories
for i in only_dir:
try:
# os.chmod(i, 0o777)
shutil.rmtree(i, ignore_errors = False) # removes the the directory and all the sub-files and sub-directory it has
except Exception as e:
print(e)
locations = ['C:\\Users\\Sahil\\AppData\\Local\\Temp', 'C:\\Windows\\Temp','C:\\Windows\\Prefetch']
# call function
delete_temp_file(locations)
That was it. Thank you for reading. ๐
I know it is a lot, but, I hope, you were able to absorb some knowledge. Let me know if you need any help or want to discuss something. Reach out to me on Twitter or LinkedIn. Make sure to share any thoughts, questions, or concerns. I would love to see them.
You can subscribe to my Newsletter for more amazing resources and articles.
Till the next time ๐
Posted on October 31, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
November 1, 2024