Python 有几个内置模块,允许您删除文件或删除目录。
本教程是使用 3 种不同方法删除文件或目录的分步指南。
os 模块shutil 模块pathlib 模块让我们看看这些模块中的每一个以及我们可以用来删除目录或文件的函数。
该os 模块是 Python 2 和 3 版本中都可用的内置实用程序,它提供了与操作系统轻松交互的功能。
os.remove() 用于在 Python 中删除或删除文件。此方法无法删除目录,如果您尝试将目录作为路径,则会引发 OSError。
语法 – os.remove(path, *, dir_fd = None)
参数: 以文件路径作为输入参数,路径可以是字符串类型。该函数不返回任何内容。
# Import os module
import os
filePath='/Projects/Tryouts/test/python.txt'
# check whethere the provided filepath exists and if its of file type
if os.path.isfile(filePath):
# delete the file using remove function
os.remove(filePath)
print("Successfully deleted a file")
else:
print("File doesn't exists!")输出
Successfully deleted a file注意 –如果您不检查isFile 或指定无效的os.remove() 方法路径 ,Python 将抛出FileNotFoundError 如下所示的a 。
Traceback (most recent call last):
File "c:\Projects\Tryouts\main.py", line 3, in <module>
os.remove(filePath)
FileNotFoundError: [WinError 2] The system cannot find the file specified: '/Projects/Tryouts/test/path_does_not_exsist.txt'os模块有一个 os.rmdir() 以法 移除或删除空目录。 如果目录不存在或发现目录不为空,您将收到 OSError。
语法:os.rmdir(path, *, dir_fd = None)
参数: 以文件夹路径作为输入参数,路径可以是字符串类型。该函数不返回任何内容。
注意 – 如果您不检查 isdir 或指定无效的os.rmdir() 方法路径 ,Python 将抛出FileNotFoundError 如下所示的a 。
# Import os module
import os
folderPath='/Projects/Tryouts/test/'
# check whethere the provided folder path exists and if its of directory type
if os.path.isdir(folderPath):
# delete the folder using rmdir function
os.rmdir(folderPath)
print("Successfully deleted a folder")
else:
print("Folder doesn't exists!")输出
Successfully deleted a folder该os 模块的缺点是您无法删除包含内容的整个目录。如果要删除目录并递归删除其中的所有文件,则应使用 shutil.rmtree() 方法。
语法:shutil.rmtree(path, ignore_errors=False, onerror=None)
参数:
ignore_errors 为 false 或省略,则通过调用onerror指定的处理程序来处理此类错误 。# Import os module
import shutil
# Directory that needs to be deleted. Removes all the files and folders inside the path
folderpath='/Projects/Tryouts/test/'
shutil.rmtree(folderpath)如果您在使用Python 3.4+版本,你可以利用 的pathlib 模块,这是作为一个内置的模块。该模块提供表示文件系统路径的类,其语义适用于不同的操作系统。
这里有两个主要功能——
pathlib 有一个方法调用Path.unlink()它删除文件或符号链接。
语法 – Path.unlink(missing_ok=False)
如果 missing_ok 为 false(默认值), 则在路径不存在时引发FileNotFoundError 。
# Import os module
import pathlib
# removes the current file path or symbolic link
file_to_remove= pathlib.Path('/Projects/Tryouts/test/python.txt')
file_to_remove.unlink()pathlib 有一个方法调用Path.rmdir()它删除指定的目录。该目录必须为空,否则会引发 OSError。
# Import os module
import pathlib
# removes the current directory if its empty
folder_to_remove= pathlib.Path('/Projects/Tryouts/test/')
folder_to_remove.rmdir()本文系外文翻译,前往查看
如有侵权,请联系 cloudcommunity@tencent.com 删除。