How to delete a CSV file in Python

To delete a file, you must import the OS module, and run its os.remove() function:

import os

os.remove("outfile.csv")

Unwritten rule: Check if file exists, then delete it

To avoid getting an error, you might want to check if the file exists before you try to delete it.

  • This can be achieved in two ways :
    • Case 1: Check if File exist.
    • Case 2: Use exception handling.

Case 1:

import os

my_file="/path/to/outfile.csv"

# check if file exists 
if os.path.exists(my_file):
    os.remove(my_file)

    # Print the statement once the file is deleted  
    print("The file: {} is deleted!".format(my_file))
else:
    print("The file: {} does not exist!".format(my_file))

output:

The file: /path/to/outfile.csv is deleted!

# or
The file: /path/to/outfile.csv does not exist!

Case 2:

import os

my_file="/path/to/outfile.csv"

## Try to delete the file
try:
    os.remove(my_file)
    print("The file: {} is deleted!".format(my_file))
except OSError as e:
    print("Error: {} - {}!".format(e.filename, e.strerror))

output:

# example of an error
Error: /path/to/outfile.csv - No such file or directory!
Error: /path/to/outfile.csv - Operation not permitted!

# successfully
The file: /path/to/outfile.csv is deleted!

Python has a tempfile facility I would check that out... But to remove a file you use os.remove():

import os
os.remove('outfile.csv')

Tags:

Python

Csv