python
主页 > 脚本 > python >

python删除目录的三种方法介绍

2024-12-09 | 佚名 | 点击:

一、os.rmdir(path)

删除目录 path,path必须是个空目录,否则抛出OSError异常。

二、os.removedirs(path) 

递归地删除目录。要求每一级目录都为空,才能递归删除全部目录。子目录被成功删除,才删除父目录;如果子目录没有成功删除,将抛出OSError异常。 

1

2

3

import os

#test2是test的子文件夹,如果test2不为空,则抛出异常;如果test2为空,test不为空,则test2删除成功,test不删除,但不报异常

os.removedirs('./test/test2)

三、shutil.rmtree(path)

不管目录path是否为空,都删除。

1

2

import shutil

shutil.rmtree('./test')  # 删除test文件夹下所有的文件、文件夹

四、删除文件

Pathlib

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

from pathlib import Path

 

# 定义要删除的文件路径

file_to_delete = Path('/home/python/test/file1.txt')

 

try:

    # 检查文件是否存在

    if file_to_delete.exists() and file_to_delete.is_file():

        # 删除文件

        file_to_delete.unlink()

        print(f"File {file_to_delete} has been deleted.")

    else:

        print(f"File {file_to_delete} does not exist or is not a file.")

except Exception as e:

    print(f"An error occurred: {e}")

os

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

import os

 

# 定义要删除的文件路径

file_to_delete = '/home/python/test/file1.txt'

 

try:

    # 检查文件是否存在

    if os.path.exists(file_to_delete) and os.path.isfile(file_to_delete):

        # 删除文件

        os.remove(file_to_delete)

        print(f"File {file_to_delete} has been deleted.")

    else:

        print(f"File {file_to_delete} does not exist or is not a file.")

except Exception as e:

    print(f"An error occurred: {e}")

 

原文链接:
相关文章
最新更新