Skip to content
Related Articles

Related Articles

Improve Article

How to delete a CSV file in Python?

  • Last Updated : 13 Jan, 2021

In this article, we are going to delete a CSV file in Python. CSV (Comma-separated values file) is the most commonly used file format to handle tabular data. The data values are separated by, (comma). The first line gives the names of the columns and after the next line the values of each column.

Approach :

  • Import module.
  • Check the path of the file.
  • If the file is existing then we will delete it with os.remove().

Syntax : os.remove(‘Path)

Example 1: Deleting specific csv file.


# Python program to delete a csv file 
# csv file present in same directory
import os
# first check whether file exists or not
# calling remove method to delete the csv file
# in remove method you need to pass file name and type
file = 'word.csv'
if(os.path.exists(file) and os.path.isfile(file)):
  print("file deleted")
  print("file not found")


file deleted

Example 2: Deleting all csv files in a directory

We can use the os.walk() function to walk through a directory and delete specific files. In the example below, we will delete all ‘.csv’ files in the given directory.


import os
for folder, subfolders, files in os.walk('csv/'): 
    for file in files: 
        # checking if file is 
        # of .txt type 
        if file.endswith('.csv'): 
            path = os.path.join(folder, file
            # printing the path of the file 
            # to be deleted 
            print('deleted : ', path )
            # deleting the csv file 


deleted :  csv/Sample1.csv
deleted :  csv/Sample2.csv
deleted :  csv/Sample3.csv
deleted :  csv/tips.csv

 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course

My Personal Notes arrow_drop_up
Recommended Articles
Page :