如何使用 Python 删除交换文件?
programmingpythonserver side programming更新于 2025/3/19 21:32:17
这篇 Python 文章将教您如何递归删除文件夹中具有特定扩展名的所有文件。
当我们为应用程序提供文件夹路径和文件扩展名时,该应用程序将删除文件夹中具有所提供扩展名的所有文件。
示例 - 使用 file.endswith() 方法
删除交换文件所涉及的步骤如下 -
- 从中导入 _os _module 和 _listdir _。要查看某个文件夹中所有文件的列表,请使用 _listdir,要删除文件,请使用 _os 模块。
- 包含所有文件的文件夹的路径称为 folderpath。
- 正在循环遍历指定文件夹中的文件。要获取某个文件夹中所有文件的单个列表,请使用命令 _listdir。
- 要确定文件是否以 .txt 扩展名结尾,请使用 endswith 函数。此"if 条件"将确保我们删除相关文件夹中的所有 .txt 文件。
- 如果文件名以 .txt 结尾,我们将使用 os.remove() 函数删除文件。文件路径是此函数的参数。我们要删除的文件的完整路径是 folderpath + filename。
以下是使用 file.endswith() 方法删除交换文件的示例 -
# importing the modules import os from os import listdir # Providing the path path = 'C:\Users\Lenovo\Downloads\Work TP\' # iterating the files in folder for file in listdir(path): # checking whether the files ends with .py extension if file.endswith('.txt'): os.remove(path + file) print("File Remoived Successfully...")
输出
执行上述代码后,我们可以看到扩展名为 .txt 的文件已从文件夹中删除。显示以下消息 -
File Remoived Successfully...
示例 - 使用 os.path.join 命令
为了确保命令理解您要查找的文件夹以执行此操作,必须将文件名添加到文件路径中。
使用 Python 中的 os.path.join 命令,您可以准确且方便地完成此任务。
.swp 是交换文件的扩展名。递归删除文件夹中所有交换文件的最简单方法是使用字符串函数 endswith 来匹配文件名和扩展名 (.swp)。
以下是使用 os.path.join 命令删除交换文件的示例 -
import os, os.path mypath = "C:\Users\Lenovo\Downloads\Work TP" for root, dirs, files in os.walk(mypath): for file in filter(lambda x: x.endswith('.txt'), files): os.remove(os.path.join(root, file)) print("File Remoived Successfully...")
输出
作为上述代码的输出,我们可以看到扩展名为 .txt 的文件已从文件夹中删除。
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

