如何在Python中删除(删除)文件和目录
Python有一些内置模块,可让我们删除文件和目录。
本教程说明如何使用'os','pathlib'和'shutil'模块中的函数删除文件和目录。
删除文件
在Python中,我们可以使用“ os.remove()”,“ os.unlink()”,“ pathlib.Path.unlink()”来删除单个文件。
“ os”模块提供了一种与操作系统进行交互的可移植方式。
该模块可用于Python 2和3.
要使用'os.remove()'删除单个文件,请将路径作为参数传递给该文件:
import os file_path = '/tmp/file.txt' os.remove(file_path)
“ os.remove()”和“ os.unlink()”函数在语义上是相同的:
import os file_path = '/tmp/file.txt' os.unlink(file_path)
如果指定的文件不存在,则会引发“ FileNotFoundError”错误。
“ os.remove()”和“ os.unlink()”都只能删除文件,不能删除目录。
如果给定的路径指向目录,则将引发“ IsADirectoryError”错误。
删除文件需要在包含文件的目录上具有写和执行权限。
否则,我们将收到“ PermissionError”错误。
为了避免在删除文件时出错,可以使用异常处理来捕获异常并发送适当的错误消息:
import os file_path = '/tmp/file.txt' try: os.remove(file_path) except OSError as e: print("Error: %s : %s" % (file_path, e.strerror))
“ pathlib”模块在Python 3.4及更高版本中可用。
如果要在Python 2中使用此模块,可以使用pip进行安装。
“ pathlib”提供了一个面向对象的接口,用于处理不同操作系统的文件系统路径。
要使用“ pathlib”模块删除文件,请创建一个指向该文件的“ Path”对象,然后在该对象上调用“ unlink()”方法:
from pathlib import Path file_path = Path('/tmp/file.txt') try: file_path.unlink() except OSError as e: print("Error: %s : %s" % (file_path, e.strerror))
'pathlib.Path.unlink()','os.remove()'和'os.unlink()'也可用于删除符号链接。
模式匹配
我们可以使用glob模块根据模式匹配多个文件。
例如,要删除“/tmp”目录中的所有“ .txt”文件,我们将使用以下内容:
import os import glob files = glob.glob('/tmp/*.txt') for f in files: try: f.unlink() except OSError as e: print("Error: %s : %s" % (f, e.strerror))
要递归删除“/tmp”目录中的所有“ .txt”文件及其下的所有子目录,请将“ recursive = True”参数传递给“ glob()”函数,并使用“ **”模式:
import os import glob files = glob.glob('/tmp/**/*.txt', recursive=True) for f in files: try: os.remove(f) except OSError as e: print("Error: %s : %s" % (f, e.strerror))
“ pathlib”模块包括两个glob函数,“ glob()”和“ rglob()”以匹配给定目录中的文件。
'glob()'仅匹配顶级目录中的文件。
“ rglob()”以递归方式匹配目录和所有子目录中的所有文件。
以下示例代码删除“/tmp”目录中的所有“ .txt”文件:
from pathlib import Path for f in Path('/tmp').glob('*.txt'): try: f.unlink() except OSError as e: print("Error: %s : %s" % (f, e.strerror))
删除目录(文件夹)
在Python中,我们可以使用'os.rmdir()'和'pathlib.Path.rmdir()'删除一个空目录,并使用'shutil.rmtree()'删除一个非空目录。
以下示例显示如何删除空目录:
import os dir_path = '/tmp/img' try: os.rmdir(dir_path) except OSError as e: print("Error: %s : %s" % (dir_path, e.strerror))
另外,我们可以使用“ pathlib”模块删除目录:
from pathlib import Path dir_path = Path('/tmp/img') try: dir_path.rmdir() except OSError as e: print("Error: %s : %s" % (dir_path, e.strerror))
“ shutil”模块允许我们对文件和目录执行许多高级操作。
使用“ shutil.rmtree()”功能,我们可以删除给定目录,包括其内容:
import shutil dir_path = '/tmp/img' try: shutil.rmtree(dir_path) except OSError as e: print("Error: %s : %s" % (dir_path, e.strerror))
传递给“ shutil.rmtree()”的参数不能是指向目录的符号链接。