Python 有一些内置模块,允许您删除文件和目录。
本教程介绍如何使用以下函数删除文件和目录os
, pathlib
, and shutil
模块。
删除文件#
在Python中你可以使用os.remove()
, os.unlink()
, pathlib.Path.unlink()
删除单个文件。
The os模块提供了一种与操作系统交互的可移植方式。该模块适用于 Python 2 和 3。
删除单个文件os.remove()
,将文件的路径作为参数传递:
import os
file_path = '/tmp/file.txt'
os.remove(file_path)
os.remove()
and os.unlink()
函数在语义上是相同的:
import os
file_path = '/tmp/file.txt'
os.unlink(file_path)
如果指定文件不存在
a FileNotFoundError
抛出错误。两个都os.remove()
and os.unlink()
只能删除文件,不能删除目录。如果给定的路径指向一个目录,它们将抛出IsADirectoryError
error.
删除文件需要对包含该文件的目录具有写入和执行权限。否则,你会得到PermissionError
error.
为了避免删除文件时出错,可以使用异常处理来捕获异常并发送正确的错误消息:
import os
file_path = '/tmp/file.txt'
try:
os.remove(file_path)
except OSError as e:
print("Error: %s : %s" % (file_path, e.strerror))
The 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()
, and os.unlink()
也可以用来删除符号链接
.
模式匹配#
您可以使用glob模块根据模式匹配多个文件。例如,删除所有.txt
文件在/tmp
目录,你会使用这样的东西:
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))
递归删除所有文件.txt
in the /tmp
目录及其下的所有子目录,传递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))
The pathlib
模块包括两个 glob 函数,glob()
and rglob()
匹配给定目录中的文件。glob()
仅匹配顶级目录中的文件。rglob()
递归地匹配目录和所有子目录中的所有文件。以下示例代码删除所有.txt
文件在/tmp
目录:
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()
and 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
module:
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))
The 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()
不能是目录的符号链接。
结论#
Python 提供了几个用于处理文件的模块。
我们已经向您展示了如何使用os.remove()
, os.unlink()
, pathlib.Path.unlink()
删除单个文件,os.rmdir()
and pathlib.Path.rmdir()
删除一个空目录并shutil.rmtree()
递归删除目录及其所有内容。
删除文件或目录时要格外小心,因为文件一旦删除,就无法轻易恢复。
如果您有任何问题或反馈,请随时发表评论。