Python提供了不同的方法和函数来删除文件和目录。因为python提供了 很多功能,我们可以删除文件和目录,根据我们的需要。例如,我们可以删除大小超过1 MB的文件。
检查文件或目录是否存在
在删除文件或目录之前,检查它是否存在是一种非常方便的方法。我们可以检查文件是否存在 exists()
系统的功能 os.path
模块。在下面的示例中,我们将检查不同的文件是否存在。
import osif os.path.exists("test.txt"): print("test.txt exist")else: print("test.txt do NOT exist")test.txt exist status = os.path.exists("test.txt")#status will be Truestatus = os.path.exists("text.txt")#status will be Falsestatus = os.path.exists("/")#status will be Truestatus = os.path.exists("/home/ismail")#status will be True
![图片[1]-如何用Python删除文件和目录?-yiteyi-C++库](https://www.yiteyi.com/wp-content/uploads/2020/05/poftut_image-39.png)
使用Remove()方法删除文件
我们可以用 os.remove()
函数以删除文件。我们应该进口 os
模块以便使用 remove
功能。在本例中,我们将删除名为 trash
.
import osos.remove("/home/ismail/readme.txt")os.remove("/home/ismail/test.txt")os.remove("/home/ismail/Pictures")#Traceback (most recent call last):# File "", line 1, in #IsADirectoryError: [Errno 21] Is a directory: '/home/ismail/Pictures'
![图片[2]-如何用Python删除文件和目录?-yiteyi-C++库](https://www.yiteyi.com/wp-content/uploads/2020/05/poftut_image-40.png)
我们可以看到,当我们试图删除名为“Pictures”的目录或文件夹时,会出现一个错误,因为remove()方法不能用于删除或删除目录或文件夹。
如果指定的文件不存在 FileNotFoundError
将作为异常抛出。另一个错误或例外是当前用户没有删除正在运行的文件的权限 remove()
函数将抛出 PermissionError
. 为了处理这种类型的错误和异常,我们应该使用 try-catch
并妥善处理。
相关文章: “pip command not found”错误解决方案适用于Linux、Debian、Ubuntu、CentOS、Mint的pip和Pip3
处理文件删除操作的异常和错误
我们可以使用try-catch块处理先前定义的错误和异常。在这一部分中,我们将处理不同的异常和相关的错误 IsADirectory
, FileNotFound
, PermissionError
.
![图片[3]-如何用Python删除文件和目录?-yiteyi-C++库](https://www.yiteyi.com/wp-content/uploads/2020/05/poftut_image-41.png)
我们可以在上面看到,每一个远程操作都会产生一个错误或异常。现在我们将正确处理所有这些异常,并打印一些有关异常的信息。
import ostry: os.remove("/home/ismail/notexist.txt")except OSError as err: print("Exception handled: {0}".format(err))# Exception handled: [Errno 2] No such file or directory: '/home/ismail/notexist.txt'try: os.remove("/etc/shadow")except OSError as err: print("Exception handled: {0}".format(err))#Exception handled: [Errno 13] Permission denied: '/etc/shadow' try: os.remove("/home/ismail/Pictures")except OSError as err: print("Exception handled: {0}".format(err)) #Exception handled: [Errno 21] Is a directory: '/home/ismail/Pictures'
![图片[4]-如何用Python删除文件和目录?-yiteyi-C++库](https://www.yiteyi.com/wp-content/uploads/2020/05/poftut_image-42.png)
删除取消链接的文件
unlink
用于删除文件。 unlink
实现 remove
. unlink
是因为实现Unix哲学而定义的。看 remove
更多信息。
用rmdir()方法删除空目录/文件夹
众所周知,Linux提供 rmdir
用于删除空目录的命令。Python在 os
模块。我们只能删除带有 rmdir
.
import osos.rmdir("/home/ismail/data")
使用rmtree()方法递归删除目录和内容
如何删除目录及其内容?我们不能使用 rmdir
因为目录不是空的。我们可以用 shutil
模块 rmtree
功能。
import shutilshutil.rmtree("/home/ismail/cache")

仅删除特定的文件类型或扩展名
删除文件时,我们可能只需要删除特定的文件类型或扩展名。我们可以用 *
用于指定文件扩展名的通配符。例如,为了删除文本文件,我们可以指定 *.txt
分机。我们也应该使用 glob
用于创建文件列表的模块和函数。
相关文章: Memcached Get Check和Set操作
在本例中,我们将列出所有具有扩展名的文件 .txt
通过使用 glob
功能。我们将使用列表名称 filelist
为了这些文件。然后在列表上循环以删除文件 remove()
一个接一个地工作。
import globimport osfilelist=glob.glob("/home/ismail/*.txt")for file in filelist: os.remove(file)
