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)