Python中删除文件和文件夹的方法

Python中删除文件和文件夹的方法

技术背景

在Python编程中,经常需要对文件和文件夹进行操作,其中删除文件和文件夹是常见的需求。Python提供了多种方法来实现这一功能,不同的方法适用于不同的场景。

实现步骤

删除文件

  • 使用os.remove()os.unlink():这两个方法在功能上基本相同,用于删除单个文件。在Python 3.3及以下版本中常用,在更高版本中也可使用。
1
2
3
4
import os
os.remove("/tmp/test.txt")
# 或者
os.unlink("/tmp/test.txt")
  • 使用pathlib.Path.unlink():适用于Python 3.4及以上版本,提供了更面向对象的方式来操作文件路径。
1
2
3
import pathlib
file_to_rem = pathlib.Path("/tmp/test.txt")
file_to_rem.unlink()

删除文件夹

  • 删除空文件夹:可以使用os.rmdir()pathlib.Path.rmdir()
1
2
import os
os.rmdir("/tmp/empty_folder")
1
2
3
from pathlib import Path
q = Path('/tmp/empty_folder')
q.rmdir()
  • 删除非空文件夹:使用shutil.rmtree(),它会递归地删除文件夹及其所有内容。
1
2
3
4
5
6
import shutil 
import os
location = "E:/Projects/PythonPool/"
dir = "Test"
path = os.path.join(location, dir)
shutil.rmtree(path)

核心代码

完整示例代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
import os
import shutil
from pathlib import Path

# 删除文件
def delete_file():
file_path = "/tmp/test.txt"
try:
if os.path.isfile(file_path):
os.remove(file_path)
print(f"文件 {file_path} 已删除")
except OSError as e:
print(f"删除文件时出错: {e}")

# 删除空文件夹
def delete_empty_folder():
folder_path = "/tmp/empty_folder"
try:
if os.path.isdir(folder_path) and not os.listdir(folder_path):
os.rmdir(folder_path)
print(f"空文件夹 {folder_path} 已删除")
except OSError as e:
print(f"删除空文件夹时出错: {e}")

# 删除非空文件夹
def delete_non_empty_folder():
folder_path = "/tmp/non_empty_folder"
try:
shutil.rmtree(folder_path)
print(f"非空文件夹 {folder_path} 已删除")
except OSError as e:
print(f"删除非空文件夹时出错: {e}")

# 使用pathlib删除文件
def delete_file_with_pathlib():
file_path = Path("/tmp/test.txt")
try:
if file_path.is_file():
file_path.unlink()
print(f"文件 {file_path} 已删除")
except FileNotFoundError:
print(f"文件 {file_path} 不存在")

if __name__ == "__main__":
delete_file()
delete_empty_folder()
delete_non_empty_folder()
delete_file_with_pathlib()

最佳实践

  • 检查文件或文件夹是否存在:在删除之前,最好先检查文件或文件夹是否存在,避免抛出异常。可以使用os.path.isfile()os.path.isdir()进行检查。
1
2
3
4
5
6
import os
myfile = "/tmp/foo.txt"
if os.path.isfile(myfile):
os.remove(myfile)
else:
print("Error: %s file not found" % myfile)
  • 异常处理:使用try-except块捕获并处理可能的异常,增强代码的健壮性。
1
2
3
4
5
6
import os
myfile = input("Enter file name to delete: ")
try:
os.remove(myfile)
except OSError as e:
print("Error: %s - %s." % (e.filename, e.strerror))

常见问题

  • 文件不存在:使用os.remove()pathlib.Path.unlink()删除不存在的文件时,会抛出FileNotFoundError异常。可以通过检查文件是否存在或设置missing_ok=True(Python 3.8及以上)来避免。
  • 文件夹非空:使用os.rmdir()pathlib.Path.rmdir()删除非空文件夹时,会抛出OSError异常。此时应使用shutil.rmtree()来删除。
  • 权限问题:如果没有足够的权限删除文件或文件夹,会抛出PermissionError异常。需要确保具有相应的权限。

Python中删除文件和文件夹的方法
https://119291.xyz/posts/2025-04-21.python-file-and-folder-deletion/
作者
ww
发布于
2025年4月22日
许可协议