如何在Python中删除文件或文件夹?

3383 投票
18 回答
3578722 浏览
提问于 2025-04-16 23:12

在Python中,我该如何删除一个文件或文件夹呢?

18 个回答

126

使用

shutil.rmtree(path[, ignore_errors[, onerror]])

(完整的文档可以查看shutil)或者

os.remove

os.rmdir

(完整的文档可以查看os。)

740

用Python语法删除文件

import os
os.remove("/tmp/<file_name>.txt")

或者

import os
os.unlink("/tmp/<file_name>.txt")

或者

pathlib库适用于Python版本 >= 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参数。

最佳实践

首先,检查文件或文件夹是否存在,然后再删除它。你可以通过两种方式来做到这一点:

  1. os.path.isfile("/path/to/file")
  2. 使用异常处理

示例:使用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))
4858

你可以使用以下方法:


如果你使用的是Python 3.3或更早的版本,可以用这些方法代替pathlib的方法:

撰写回答