Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

How to delete a folder by python

Shulou Source: shulou.com Published: 2022-05-31 11:12:48 09月23日 Update

This article mainly introduces the relevant knowledge of python how to delete a folder, the content is detailed and easy to understand, the operation is simple and fast, and has a certain reference value, I believe you will gain something after reading this python article on how to delete a folder, let's take a look at it.

Specific operation methods:

1. First of all, you need to import the os module in the python script for file operation.

Import os

2. Then if statement to determine whether the folder to be deleted is empty.

3. Finally, use the os.listdir () method to get the empty folder and delete the folder through the rmdir function.

The code example is as follows:

#! / usr/bin/python

Import os

# getting the folder path from the user

Folder_path = input ("Enter folder path:-")

# checking whether folder exists or not

If os.path.exists (folder_path):

# checking whether the folder is empty or not

If len (os.listdir (folder_path)) = = 0:

# removing the file using the os.remove () method

Os.rmdir (folder_path)

Else:

# messaging saying folder not empty

Print ("Folder is not empty")

Else:

# file not found message

Print ("File not found in the directory")

Related functions:

Os.remove # Delete files

Os.rmdir # Delete folder

Shutil.rmtree # Delete the directory and all its contents

This is the end of the article on "how to delete folders in python". Thank you for reading! I believe you all have a certain understanding of "how to delete folders in python". If you want to learn more, you are welcome to follow the industry information channel.

Tags: Files folders content knowledge functions methods articles code value easy to operate articles easy to understand more modules directories see examples scripts industries statements Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno macOS Shulou Information MariaDB Docker Apple