Python中7删除文件的7种方法实现与对比

 更新时间:2025年09月05日 08:43:01   作者:Python资讯站  
本文提供了有关如何使用各种模块和方法在Python中删除文件的详尽教程,文中的示例代码简洁易懂,感兴趣的小伙伴可以跟随小编一起学习一下

除了"rm -rf"你还知道那些删库跑路的方法?

本文提供了有关如何使用各种模块和方法在Python中删除文件的详尽教程。它介绍了使用"os.remove()"和"os.unlink()"等简单技术、用于目录的"pathlib.Path.unlink()"和"shutil.rmtree()"等更复杂的技术,以及用于将文件放入回收站的"send2trash"等更安全的选项。它还介绍了如何使用 tempfile 管理临时文件以及如何处理符号链接。在本文中,我们将探讨在Python中删除文件的方法。

概述

  • 了解使用 os.remove()os.unlink() 的Python中的基本文件删除方法。
  • 了解如何使用shutil.rmtree() 递归删除整个目录及其内容。
  • 了解使用 os.unlink() 删除符号链接的过程。
  • 使用 pathlib.Path.unlink() 作为文件删除的一种现代且可读的方法。
  • 使用 send2trash 将文件发送到回收站以安全删除它们,以便在需要时进行恢复。
  • 使用 tempfile 模块创建并自动删除临时文件。

在Python中删除文件

1.使用 os.remove()

os.remove() 是Python的一种方法,用于从文件系统中永久删除文件。它需要导入 os 模块并提供文件路径。使用 os.path.exists() 检查文件是否存在,避免发生异常。如果存在,os.remove(file_path) 将删除它并显示确认消息。

import os                     # Specify the file name  
file_path = 'example.txt'     # Check if the file exists before attempting to delete it  
if os.path.exists(file_path): # Delete the file  
os.remove(file_path)  
print(f"{file_path} has been deleted successfully.")  
else:  
print(f"{file_path} does not exist.")  

解释:

使用 os.path.exists(file_path) 函数确定指定路径上是否存在文件。如果文件已存在,Python 将使用 将其删除os.remove(file_path)。如果文件丢失,它将打印一条通知,表明该文件不存在。

注意:

  • 如果找不到文件,此过程将引发异常。因此,在尝试删除文件之前,最好先验证文件是否存在。
  • 当你希望永久删除文件时可以使用此方法。

2.使用 os.unlink()

使用python中的 os.unlink()可以从文件系统中永久删除文件。第一步是导入 OS 模块。然后必须使用 os.path.exists() 验证文件是否存在。找到文件后,os.unlink(file_path) 会将其删除并显示确认消息。

import os                      # Specify the file name  
file_path = 'example.txt'    
if os.path.exists(file_path):  
                               # Delete the file  
os.unlink(file_path)  
print(f"{file_path} has been deleted successfully.")  
else:  
print(f"{file_path} does not exist.")  

解释:

  • os.unlink(file_path) 函数删除参数 file_path 指定的文件。
  • os.remove() 一样,如果文件不存在,它会引发异常。

注意:

os.unlink()os.remove() 在删除文件方面功能相同。

根据你的偏好或编码风格,可以将此方法与os.remove()交替使用。

3.使用shutil.rmtree()

在 Python 中,可以使用该方法递归删除目录及其内容shutil.rmtree()。该方法用于删除文件、子目录和目录。通过运行 os.path.exists(directory_path) 确保目录在使用前存在。虽然方法很强大,但请谨慎使用。

import shutil                       # Specify the directory path  
directory_path = 'example_directory'    
if os.path.exists(directory_path):  # Delete the directory and its contents  
shutil.rmtree(directory_path)  
print(f"{directory_path} has been deleted successfully.")  
else:  
print(f"{directory_path} does not exist.")  

解释:

  • shutter.rmtree(directory_path) 函数删除参数directory_path指定的目录及其所有内容。
  • 如果目录不存在,则会引发异常。

注意:

  • 使用shutil.rmtree()时要小心,因为它会永久删除文件和目录。
  • 当你想要递归删除目录及其所有内容时请使用此方法。

4.使用 os.unlink() 进行符号链接

在 Python 中使用 os.unlink() 可删除符号链接,而不会影响目标文件或目录。此模块还会在删除符号链接之前检查其是否存在。此方法可用于将符号链接与常规文件分开管理,确保仅删除链接。

import os                               # Specify the symbolic link path  
symbolic_link_path = 'example_link'     # Check if the symbolic link exists before attempting to delete it  
if os.path.exists(symbolic_link_path):  # Delete the symbolic link  
os.unlink(symbolic_link_path)  
print(f"{symbolic_link_path} has been deleted successfully.")  
else:  
print(f"{symbolic_link_path} does not exist.")  

解释:

  • os.unlink(symbolic_link_path) 函数删除由symbolic_link_path指定的符号链接。
  • 如果符号链接不存在,则会引发异常。

注意:

当你想要删除符号链接时请使用此方法。

5.使用 pathlib.Path.unlink()

Python 中的 pathlib.Path.unlink() 提供了一种现代、直观的文件删除方法。要为所选文件构建 Path 对象,它导入 Path 类。unlink()如果文件存在,该方法将删除该文件。

from pathlib import Path         # Specify the file path  
file_path = Path('example.txt')  # Check if the file exists before attempting to delete it  
if file_path.exists():           # Delete the file  
file_path.unlink()  
print(f"{file_path} has been deleted successfully.")  
else:  
print(f"{file_path} does not exist.")  

解释:

  • Path(file_path)为指定的文件路径创建一个对象。
  • file_path.exists()检查文件是否存在。
  • file_path.unlink()删除文件。

注意:

pathlib与之相比,它提供了一种更现代、更易读的方式来处理文件系统路径os

6.使用 send2trash

将文件发送到垃圾箱或回收站是使用 Pythonsend2trash函数彻底删除文件的更安全的方法。安装模块、导入函数,并在提交文件之前确认它存在。

pip install send2trash  
from send2trash 
import send2trash             # Specify the file path  
file_path = 'example.txt'     # Check if the file exists before attempting to delete it  
if os.path.exists(file_path): # Send the file to the trash  
send2trash(file_path)  
print(f"{file_path} has been sent to the trash.")  
else:  
print(f"{file_path} does not exist.")  

解释:

send2trash(file_path)将指定的文件发送到垃圾/回收站。

注意:

当你希望以更安全的方式删除文件但仍允许从垃圾箱中恢复时,请使用此过程。

7.使用临时文件

Python 中的模块tempfile允许你创建临时文件和目录,这些文件和目录在使用后会自动清理。从而使它们适用于测试期间的短期数据存储或非永久性数据工作,并防止混乱。

import tempfile                                       # Create a temporary file  
temp_file = tempfile.NamedTemporaryFile(delete=True)  # Write data to the temporary file  
temp_file.write(b'This is some temporary data.')  
temp_file.seek(0)                                     # Read the data back  
print(temp_file.read())                               # Close the temporary file (it gets deleted automatically)  
temp_file.close()  

解释:

  • tempfile.NamedTemporaryFile(delete=True)关闭时将删除创建的临时文件。
  • 与任何其他文件一样,你可以写入和读取临时文件。
  • 调用时临时文件会被自动删除temp_file.close()

注意:

对于使用后需要自动删除的临时文件请使用此方法。

在Python中有多种方法可以删除文件。通过os.remove()os.unlink()例程提供了永久删除文件的简单技术。可以使用shutil.rmtree()函数管理整个目录。os.unlink()可消除符号链接,而不会影响预期结果。一种面向对象的现代方法是pathlib.Path.unlink()。使用send2trash将文件发送到回收站,以便可以恢复。临时文件由tempfile自动管理。

到此这篇关于Python中7删除文件的7种方法实现与对比的文章就介绍到这了,更多相关Python删除文件内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • python运行加速的几种方式

    python运行加速的几种方式

    Python运行的慢是历来被诟病的,本文就来介绍一下python运行加速的几种方式,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2021-07-07
  • Python自动化测试笔试面试题精选

    Python自动化测试笔试面试题精选

    在本篇文章里小编给大家整理的是一篇关于Python自动化测试笔试面试时常见的编程题,需要的朋友们可以学习参考下。
    2020-03-03
  • Python数据分析之绘制ppi-cpi剪刀差图形

    Python数据分析之绘制ppi-cpi剪刀差图形

    这篇文章主要介绍了Python数据分析之绘制ppi-cpi剪刀差图形,ppi-cp剪刀差是通过这个指标可以了解当前的经济运行状况,下文更多详细内容介绍需要的小伙伴可以参考一下
    2022-05-05
  • Python爬虫程序中使用生产者与消费者模式时进程过早退出的问题

    Python爬虫程序中使用生产者与消费者模式时进程过早退出的问题

    本文主要介绍了Python爬虫程序中使用生产者与消费者模式时进程过早退出的问题,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2023-01-01
  • TensorFlow人工智能学习张量及高阶操作示例详解

    TensorFlow人工智能学习张量及高阶操作示例详解

    这篇文章主要为大家介绍了TensorFlow人工智能学习张量及高阶操作的示例详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步
    2021-11-11
  • python中requests爬去网页内容出现乱码问题解决方法介绍

    python中requests爬去网页内容出现乱码问题解决方法介绍

    这篇文章主要介绍了python中requests爬去网页内容出现乱码问题解决方法,
    2017-10-10
  • FFrpc python客户端lib使用解析

    FFrpc python客户端lib使用解析

    这篇文章主要介绍了FFrpc python客户端lib使用解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2019-08-08
  • Python 5种常见字符串去除空格操作的方法

    Python 5种常见字符串去除空格操作的方法

    这篇文章主要给大家分享的是Python 5种常见字符串去除空格操作的方法,包括有strip()方法、rstrip()方法、replace()方法、join()方法+split()方法,下面文章是详细内容,需要的朋友可以参考一下
    2021-11-11
  • 在python中使用xlrd获取合并单元格的方法

    在python中使用xlrd获取合并单元格的方法

    今天小编就为大家分享一篇在python中使用xlrd获取合并单元格的方法,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2018-12-12
  • Python条件分支 if 语句全讲解(一文掌握)

    Python条件分支 if 语句全讲解(一文掌握)

    在Python编程中,布尔运算符有明确的优先级顺序,影响代码逻辑判断,从高到低依次是:括号()、not、and、or,括号用于明确运算顺序,not具有次高优先级,影响单个布尔值,and和or则根据优先级顺序结合布尔值,正确理解和应用这些优先级对于编写有效和准确的条件语句至关重要
    2024-10-10

最新评论