多方位详解shutil删除文件

发布时间:2023-05-19

一、跨平台操作

shutil模块是Python自带的一个高级文件操作工具,其中,shutil.rmtree(path, ignore_errors=False, onerror=None)方法可以删除一个目录及其子目录和文件,其可以跨平台操作,适用于Windows,Linux,Mac OS等操作系统,因此在开发跨平台应用时非常有用。

import os
import shutil
dir_path = "test_dir"
os.makedirs(dir_path)
file_path = "test_file.txt"
with open(file_path, "w") as f:
    f.write("hello world")
shutil.rmtree(dir_path)
os.remove(file_path)

上述代码示例中创建了一个test_dir目录和一个test_file.txt文件,最后通过shutil.rmtree和os.remove方法分别删除了目录和文件,该代码在Windows,Linux,Mac OS系统下均可运行。

二、避免误删除

shutil.rmtree方法删除目录时,如果未传入ignore_errors=True参数,它会在目录不存在或者打开目录失败时抛出异常,这有助于避免误删除问题。

import os
import shutil
dir_path = "test_dir"
os.makedirs(dir_path)
# 删除不存在的目录
try:
    shutil.rmtree("test")
except Exception as e:
    print(e)
# 删除目录失败
try:
    os.chdir(dir_path)
    shutil.rmtree("..")
except Exception as e:
    print(e)
shutil.rmtree(dir_path, ignore_errors=True)

上述代码示例中首先创建了一个test_dir目录,之后尝试删除不存在的test目录和存在但是打开失败的test_dir上级目录,最后通过ignore_errors=True参数删除了test_dir目录。

三、删除只读文件

在Windows系统下,文件属性可能会被设置为只读,此时我们无法直接删除该文件。不过shutil模块提供了chattr方法用于修改文件属性,从而实现删除文件的功能。

import os
import shutil
# 创建只读文件
file_path = "test.txt"
with open(file_path, "w") as f:
    f.write("hello world")
os.chmod(file_path, 0o440)
# 删除只读文件
os.chmod(file_path, 0o777)
os.remove(file_path)

上述代码示例中首先创建了一个只读文件test.txt,之后通过os.chmod方法修改文件权限为0o777,从而实现删除文件的功能。

四、删除文件夹下指定类型文件

在操作文件夹时,有时候我们只需要删除文件夹下指定类型的文件,可以通过遍历文件夹并筛选出指定类型文件的方式实现此功能。

import os
import shutil
dir_path = "test_dir"
os.makedirs(dir_path)
file1_path = os.path.join(dir_path, "test1.txt")
with open(file1_path, "w") as f:
    f.write("hello world")
file2_path = os.path.join(dir_path, "test2.txt")
with open(file2_path, "w") as f:
    f.write("hello world")
file3_path = os.path.join(dir_path, "test3.md")
with open(file3_path, "w") as f:
    f.write("hello world")
for root, dirs, files in os.walk(dir_path):
    for name in files:
        if name.endswith(".txt"):
            os.remove(os.path.join(root, name))
shutil.rmtree(dir_path)

上述代码示例中创建了一个test_dir目录,其中包含了三个不同类型的文件,之后通过os.walk沿着目录树遍历文件夹,通过name.endswith(".txt")筛选出指定类型的文件并删除。

五、安全删除文件

在删除文件时,有时候为防止误删除,我们需要在删除前先备份文件再删除,此时可以使用shutil.move实现文件的备份和删除。

import os
import shutil
file_path = "test.txt"
with open(file_path, "w") as f:
    f.write("hello world")
backup_path = shutil.move(file_path, file_path + ".bak")
os.remove(backup_path)

上述代码示例中首先创建了一个test.txt文件,之后使用shutil.move方法将该文件备份为test.txt.bak,最后删除备份文件test.txt.bak。

六、解决Windows文件夹路径斜杠问题

在Windows系统下,文件夹路径使用“\”斜杆作为分隔符,在Linux和Mac OS系统下则使用“/”斜杆作为分隔符,可以使用os.path.join方法解决跨平台路径问题。

import os
import shutil
dir_path = os.path.join("test_dir", "sub_dir")
os.makedirs(dir_path)
file_path = os.path.join(dir_path, "test.txt")
with open(file_path, "w") as f:
    f.write("hello world")
shutil.rmtree(dir_path)

上述代码示例中使用os.path.join方法生成跨平台路径,确保在不同系统下依然可以正确创建文件。