12

I'm doing a project which requires me to add, delete data that is in a CSV file, the way I have done it is by creating a new CSV file called outfile.csv, which holds all the information from another CSV file called infile.csv (outfile.csv has some rows which I deleted), so outfile.csv is basically a temp file.

Is there anyway I could delete the CSV file (I've seen a few questions like these but all the answers say to just truncate the CSV file)?

Here's my code:

__row_num1 = __row_num.get()
FIRST_ROW_NUM = 1
rows_to_delete = {__row_num1}

with open("./user_info/" + Username + ".csv", "rt") as infile, open('outfile.csv', 'wt') as outfile:
    outfile.writelines(row for row_num, row in enumerate(infile, FIRST_ROW_NUM)if row_num not in rows_to_delete)
infile.close()
outfile.close()

USER_INFO_FILE = open("outfile.csv")
outfile_dict = []
read_file = csv.reader(USER_INFO_FILE)

for row in read_file:
    outfile_dict.append(row)
USER_INFO_FILE.close


f = open("./user_info/" + Username + ".csv", "w")
f.truncate()
f.close

writer = csv.writer(open("./user_info/" + Username + ".csv", "ab"), delimiter=',')
writer.writerows(outfile_dict)
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343

2 Answers2

27

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')
AChampion
  • 29,683
  • 4
  • 59
  • 75
  • Thanks a lot @AChampion for your suggestions...One query to ask..Does "os.remove" command permanently delets the file? – Ranjan Pal Dec 25 '20 at 04:22
3

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!
Milovan Tomašević
  • 6,823
  • 1
  • 50
  • 42