Delete files and directories using Python

Mini Project | Python 101 Series

Delete files & directories using Python
Delete files & directories using Python

So far, we have learned many basic concepts of Python. We learned about:

  1. Data types & Variables
  2. String Manipulation Methods
  3. List & Dictionary Manipulation Methods
  4. Conditional Statements
  5. Loops
  6. 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

  1. How can we list all the files and directories of a specific location using the os module
  2. Separate files and directories, and add them to their respective lists using the isfile() method
  3. Go through these lists of files and directories using for loop
  4. Delete files using the os module
  5. 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 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 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 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

Reusability 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 .

https://medium.com/media/1e19cbca3102dfeb593340bfbb70414e/href

Finally! We are at the end of this section 😁.

That was it. Thank you for reading.

Let me know if you need any help or want to discuss something. Reach out to me on Twitter or LinkedIn. Make sure to leave any thoughts, questions, or concerns in the comments below. I would love to see them.

Want to learn more?

Signup for my Newsletter and get the best articles into your inbox.

Till the next time 👋

Explore my other blogs from Python 101 series


Delete files and directories using Python was originally published in Level Up Coding on Medium, where people are continuing the conversation by highlighting and responding to this story.


This content originally appeared on Level Up Coding - Medium and was authored by Sahil Fruitwala

Mini Project | Python 101 Series

Delete files & directories using Python
Delete files & directories using Python

So far, we have learned many basic concepts of Python. We learned about:

  1. Data types & Variables
  2. String Manipulation Methods
  3. List & Dictionary Manipulation Methods
  4. Conditional Statements
  5. Loops
  6. 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

  1. How can we list all the files and directories of a specific location using the os module
  2. Separate files and directories, and add them to their respective lists using the isfile() method
  3. Go through these lists of files and directories using for loop
  4. Delete files using the os module
  5. 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 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 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 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

Reusability 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 .

Finally! We are at the end of this section 😁.

That was it. Thank you for reading.

Let me know if you need any help or want to discuss something. Reach out to me on Twitter or LinkedIn. Make sure to leave any thoughts, questions, or concerns in the comments below. I would love to see them.

Want to learn more?
Signup for my Newsletter and get the best articles into your inbox.

Till the next time 👋

Explore my other blogs from Python 101 series

Delete files and directories using Python was originally published in Level Up Coding on Medium, where people are continuing the conversation by highlighting and responding to this story.


This content originally appeared on Level Up Coding - Medium and was authored by Sahil Fruitwala


Print Share Comment Cite Upload Translate Updates
APA

Sahil Fruitwala | Sciencx (2022-07-18T00:30:32+00:00) Delete files and directories using Python. Retrieved from https://www.scien.cx/2022/07/18/delete-files-and-directories-using-python/

MLA
" » Delete files and directories using Python." Sahil Fruitwala | Sciencx - Monday July 18, 2022, https://www.scien.cx/2022/07/18/delete-files-and-directories-using-python/
HARVARD
Sahil Fruitwala | Sciencx Monday July 18, 2022 » Delete files and directories using Python., viewed ,<https://www.scien.cx/2022/07/18/delete-files-and-directories-using-python/>
VANCOUVER
Sahil Fruitwala | Sciencx - » Delete files and directories using Python. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2022/07/18/delete-files-and-directories-using-python/
CHICAGO
" » Delete files and directories using Python." Sahil Fruitwala | Sciencx - Accessed . https://www.scien.cx/2022/07/18/delete-files-and-directories-using-python/
IEEE
" » Delete files and directories using Python." Sahil Fruitwala | Sciencx [Online]. Available: https://www.scien.cx/2022/07/18/delete-files-and-directories-using-python/. [Accessed: ]
rf:citation
» Delete files and directories using Python | Sahil Fruitwala | Sciencx | https://www.scien.cx/2022/07/18/delete-files-and-directories-using-python/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.