如何删除文件或文件夹?
当前回答
为了避免Éric Araujo评论中强调的TOCTOU问题,您可以捕捉一个异常来调用正确的方法:
def remove_file_or_dir(path: str) -> None:
""" Remove a file or directory """
try:
shutil.rmtree(path)
except NotADirectoryError:
os.remove(path)
因为shutil.rmtree()将只删除目录,os.remove()或os.unlink()将仅删除文件。
其他回答
os.remove()删除文件。os.rmdir()删除空目录。shutil.rmtree()删除目录及其所有内容。
Python 3.4+pathlib模块中的路径对象还公开了以下实例方法:
pathlib.Path.unlink()删除文件或符号链接。pathlib.Path.rmdir()删除空目录。
Use
shutil.rmtree(path[, ignore_errors[, onerror]])
(参见shutil的完整文档)和/或
os.remove
and
os.rmdir
(操作系统的完整文档)
您可以使用内置的pathlib模块(需要Python 3.4+,但PyPI上有旧版本的后端:pathlib、pathlib2)。
要删除文件,可以使用unlink方法:
import pathlib
path = pathlib.Path(name_of_file)
path.unlink()
或使用rmdir方法删除空文件夹:
import pathlib
path = pathlib.Path(name_of_folder)
path.rmdir()
用于删除文件的Python语法
import os
os.remove("/tmp/<file_name>.txt")
or
import os
os.unlink("/tmp/<file_name>.txt")
or
用于Python的pathlib库版本>=3.4
file_to_rem = pathlib.Path("/tmp/<file_name>.txt")
file_to_rem.unlink()
Path.unlink(missing_ok=False)
用于删除文件或符号链接的Unlink方法。
如果missing_ok为false(默认值),则在路径不存在时引发FileNotFoundError。如果missing_ok为true,则将忽略FileNotFoundError异常(行为与POSIX rm-f命令相同)。在版本3.8中更改:添加了missing_ok参数。
最佳实践
首先,检查文件或文件夹是否存在,然后将其删除。可以通过两种方式实现:
os.path.isfile(“/path/to/file”)使用异常处理。
os.path.isfile示例
#!/usr/bin/python
import os
myfile = "/tmp/foo.txt"
# If file exists, delete it.
if os.path.isfile(myfile):
os.remove(myfile)
else:
# If it fails, inform the user.
print("Error: %s file not found" % myfile)
异常处理
#!/usr/bin/python
import os
# Get input.
myfile = raw_input("Enter file name to delete: ")
# Try to delete the file.
try:
os.remove(myfile)
except OSError as e:
# If it fails, inform the user.
print("Error: %s - %s." % (e.filename, e.strerror))
各自的输出
Enter file name to delete : demo.txt Error: demo.txt - No such file or directory. Enter file name to delete : rrr.txt Error: rrr.txt - Operation not permitted. Enter file name to delete : foo.txt
用于删除文件夹的Python语法
shutil.rmtree()
shutil.rmtree()示例
#!/usr/bin/python
import os
import sys
import shutil
# Get directory name
mydir = raw_input("Enter directory name: ")
# Try to remove the tree; if it fails, throw an error using try...except.
try:
shutil.rmtree(mydir)
except OSError as e:
print("Error: %s - %s." % (e.filename, e.strerror))
下面是一个同时使用os.remove和shutil.rmtree的健壮函数:
def remove(path):
""" param <path> could either be relative or absolute. """
if os.path.isfile(path) or os.path.islink(path):
os.remove(path) # remove the file
elif os.path.isdir(path):
shutil.rmtree(path) # remove dir and all contains
else:
raise ValueError("file {} is not a file or dir.".format(path))