# How to remove swap files using Python?

This Python article will teach you how to recursively remove all files in a folder that have a particular extension.

The application will remove all files with the supplied extension inside the folder when we give it the folder path and file extension.

## Example - using file.endswith() method

The steps involved to remove swap files are as follows −

• Import the _os _module and _listdir _from it. To view a list of all files in a certain folder, use _listdir, and to delete a file, use _os module.
• The path to the folder containing all files is called folderpath.
• The files in the specified folder are being looped through. To acquire a single list of all the files in a certain folder, use the command _listdir.
• To determine whether a file ends with a.txt extension or not, use the endswith function. This "if condition" will make sure we are deleting all.txt files in the folder in question.
• We are deleting the file using the os.remove() function if the file name ends in.txt. The file path is a parameter for this function. The full path for the file we are removing is folderpath + filename.

Following is an example to remove swap files using file.endswith() method −

# 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...")


## Output

On executing the above code we can see that the files with .txt extension gets deleted from the folder. Displaying the following message −

File Remoived Successfully...


## Example - using os.path.join command

To ensure that the command understands the folder you are looking in for this operation, the file name must be added to the file path.

Using the os.path.join command in Python, you may complete this task accurately and portably.

.swp is the extension for swap files. The simplest method to delete all of the swap files in a folder recursively is to use the string function endswith to match file names and the extension name(.swp).

Following is an example to remove swap files using os.path.join command −

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...")


## Output

As an output of the above code we can see that the files with .txt extension gets deleted from the folder. Displaying the following message −

File Removed Successfully...

irectory, &quot;my_folder&quot; and delete all files that end with .swp.</p>

Advertisements