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.
Python3
import os
file = 'word.csv'
if (os.path.exists( file ) and os.path.isfile( file )):
os.remove( file )
print ( "file deleted" )
else :
print ( "file not found" )
|
Output:
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.
Python3
import os
for folder, subfolders, files in os.walk( 'csv/' ):
for file in files:
if file .endswith( '.csv' ):
path = os.path.join(folder, file )
print ( 'deleted : ' , path )
os.remove(path)
|
Output:
deleted : csv/Sample1.csv
deleted : csv/Sample2.csv
deleted : csv/Sample3.csv
deleted : csv/tips.csv