如何使用 Python 删除交换文件?


本文将教你如何使用 Python 递归删除文件夹中所有具有特定扩展名的文件。

当我们提供文件夹路径和文件扩展名时,应用程序将删除文件夹内所有具有指定扩展名的文件。

示例 - 使用 file.endswith() 方法

删除交换文件的步骤如下:

  • 导入 _os_ 模块并从中导入 _listdir_。使用 _listdir_ 查看特定文件夹中所有文件的列表,并使用 _os_ 模块删除文件。
  • 包含所有文件的文件夹的路径称为 folderpath。
  • 正在循环遍历指定文件夹中的文件。使用 _listdir_ 命令获取特定文件夹中所有文件的单个列表。
  • 使用 endswith 函数确定文件是否以 .txt 扩展名结尾。此“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 的文件被删除。显示以下消息:

File Removed Successfully...
目录,“my_folder”并删除所有以 .swp 结尾的文件。

更新于: 2022年8月17日

630 次查看

启动您的 职业生涯

通过完成课程获得认证

开始
广告

© . All rights reserved.