How to remove swap files using Python?

PythonServer Side ProgrammingProgramming

Swap files have the extension .swp. Easiest way to remove all swap files from a folder recursively is to use the string function endswith with the extension name(.swp) to match file names and delete these files. 


import os, os.path
mypath = "my_folder"
for root, dirs, files in os.walk(mypath):
    for file in filter(lambda x: x.endswith('.swp'), files):
        os.remove(os.path.join(root, file))

This program will recursively search the directory, "my_folder" and delete all files that end with .swp.

Published on 27-Dec-2017 16:19:07