Explain several methods of deleting files in Python

coldplay.xixi
Release: 2021-03-17 10:19:27
forward
45506 people have browsed it

Explain several methods of deleting files in Python

Many times developers need to delete files. Maybe he created the file by mistake or the file is no longer needed. Whatever the reason, there are ways to delete files through Python without having to manually find the file and interact with the UI to delete it.

(Free learning recommendation: python video tutorial)

There are many ways to delete files using Python, but the best method is as follows:

  • os.remove() Delete the file

  • os.unlink() Delete the file. It is the Unix name of the remove() method.

  • shutil.rmtree() Deletes the directory and all contents below it.

  • pathlib.Path.unlink() Used in Python 3.4 and later to delete a single file pathlib module.

os.remove()Delete files

The OS module in Python provides functions for interacting with the operating system Function. OS belongs to Python's standard utility modules. This module provides a portable way to use operating system-dependent functionality.

os.remove() method in Python is used to remove file paths. This method cannot delete directories. If the specified path is a directory, this method will raise OSError.

Note: Directories can be deleted using os.rmdir() .

Syntax:

The following is the syntax for the remove() method to delete Python files:

os.remove(path)
Copy after login

Parameters

  • path - This is the path or file name to be deleted.

Return value

remove()The method has no return value.

Let’s look at some examples of using the os.remove function to delete Python files.

Example 1: Basic example of removing a file using the OS.Remove() method.

# Importing the os library
import os

# Inbuilt function to remove files
os.remove("test_file.txt")
print("File removed successfully")
Copy after login

Output:

File removed successfully
Copy after login

Description: In the above example, we deleted the file or deleted the file named testfile.txtThe path of the file. The steps to explain the program flow are as follows:

1. First, we imported the os library, because the remove() method exists in the os library.

2. Then, we use the built-in function os.remove() to remove the path of the file.

3. In this example, our sample file is "test_file.txt". You can place the required files here.

Note: The above example will throw an error if there is no file named test_file.txt. Therefore, it is better to check if the file is available before deleting it.

Example 2: Check if the file exists using Os.Path.Isfile and remove it using Os.Remove

In example 1, we have just deleted the files present in the directory. os.remove()The method will search the working directory for the file to be removed. So it's better to check if the file exists.

Let us learn how to check if a file with a specific name is available in that path. We are using os.path.isfile to check file availability.

#importing the os Library
import os

#checking if file exist or not
if(os.path.isfile("test.txt")):
    
    #os.remove() function to remove the file
    os.remove("demo.txt")
    
    #Printing the confirmation message of deletion
    print("File Deleted successfully")
else:
print("File does not exist")
#Showing the message instead of throwig an error
Copy after login

Output:

File Deleted successfully
Copy after login

In the above example, we only added the os.pasth.isfile() method. This method helps us find out whether a file exists in a specific location.

Example 3: Python program to delete all files with a specific extension

import os 
from os import listdir
my_path = 'C:\Python Pool\Test\'

for file_name in listdir(my_path):
    
    if file_name.endswith('.txt'):
      
        os.remove(my_path + file_name)
Copy after login

Output:

Using this program, We will delete all files with the extension .txt from the folder.

Explanation:

  • Import the os module and listdir from the os module. listdir must be used to get a list of all files in a specific folder, and the os module is required to delete files.

  • my_path is the path to the folder that contains all the files.

  • We are iterating through the files in a given folder. listdirUsed to get a list of all files in a specific folder.

  • endswith is used to check whether the file ends with the .txt extension. This is done if the condition can be verified when we delete all .txt files in the folder.

  • If the file name ends with the .txt extension, we will use the os.remove() function to delete the file. This function takes the path to the file as parameter. my_path file_name is the full path of the file we want to delete.

Example 4: Python Program to Delete All Files in a Folder

To delete all files in a specific directory, just use * symbols as pattern strings.

#Importing os and glob modules
import os, glob

#Loop Through the folder projects all files and deleting them one by one
for file in glob.glob("pythonpool/*"):
    os.remove(file)
    print("Deleted " + str(file))
Copy after login

Output:

Deleted pythonpool\test1.txt
Deleted pythonpool\test2.txt
Deleted pythonpool\test3.txt
Deleted pythonpool\test4.txt
Copy after login

In this example, we will delete all files in the pythonpool folder.

注意:如果文件夹包含其他子文件夹,则可能会报错,因为glob.glob()方法将获取所有文件夹内容的名称,无论它们是文件还是子文件夹。因此,请尝试使模式更具体(例如*.*),以仅获取具有扩展名的内容。

使用os.unlink()删除Python文件

os.unlink()os.remove()的别名。在Unix OS中,删除也称为unlink

注意:所有功能和语法与os.unlink()os.remove()相同。它们都用于删除Python文件路径。两者都是Python标准库的os模块中执行删除功能的方法。

它有两个名称,别名:os.unlink()os.remove()

为同一个函数提供两个别名的可能原因是,该模块的维护者认为,许多程序员可能会从C的底层编程转向Python,其中库函数和底层系统调用称为unlink(),而其他人则可能会使用rm命令(“删除”的缩写)或shell脚本来简化语言。

使用shutil.rmtree()删除Python文件

shutil.rmtree():删除指定的目录,所有子目录和所有文件。此功能特别危险,因为它无需检查即可删除所有内容。结果,您可以使用此功能轻松丢失数据。

rmtree()是shutil模块下的一种方法,该方法以递归方式删除目录及其内容。

句法:

Shutil.rmtree(path,ignore_errors = False,onerror = None)
Copy after login

参数:

path:类似路径的对象,表示文件路径。类路径对象是表示路径的字符串或字节对象。

ignore_errors:如果ignore_errorstrue,则删除失败导致的错误将被忽略。

oneerror:如果ignore_errorsfalse或被忽略,则通过调用onerror指定的处理程序来处理此类错误。

我们来看一个使用python脚本删除文件的示例。

示例:使用Shutil.Rmtree()删除文件的Python程序

# Python program to demonstrate shutil.rmtree() 
 
import shutil 
import os 
 
# location 
location = "E:/Projects/PythonPool/"
 
# directory 
dir = "Test"
 
# path 
path = os.path.join(location, dir) 
 
# removing directory 
shutil.rmtree(path)
Copy after login

输出:

它将删除Test内文件的整个目录,包括Test文件夹本身。

Python中使用pathlib.Path.unlink()删除文件

pathlib模块在Python 3.4及更高版本中可用。如果要在Python 2中使用此模块,可以使用pip进行安装。pathlib提供了一个面向对象的界面,用于处理不同操作系统的文件系统路径。

要使用pathlib模块删除文件,请创建一个指向该文件的Path对象,然后对该对象调用unlink()方法:

示例:使用Pathlib删除文件的Python程序

#Example of file deletion by pathlib
 
import pathlib
 
rem_file = pathlib.Path("pythonpool/testfile.txt")

rem_file.unlink()
Copy after login

在上面的示例中,path()方法用于检索文件路径,而unlink()方法用于删除指定路径的文件。

unlink()方法适用于文件。如果指定了目录,则会引发OSError。要删除目录,我们可以采用前面讨论的方法之一。

结论

在本文中,我们学习了Python删除文件的各种方法。使用Python删除文件或文件夹的语法非常简单。但是,请注意,一旦执行上述命令,您的文件或文件夹将被永久删除。

如果您仍然对Python删除文件有任何疑问。请在下面的评论部分中告诉我们。

大量免费学习推荐,敬请访问python教程(视频)

The above is the detailed content of Explain several methods of deleting files in Python. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:csdn.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template