I am trying to create an archive to store a list of available books in the system. I want my program to ask the user to input csv file, read a list of books from that file, check the year of publication and delete the row if the book is older than 7 years. I want to keep everything in a single file.
So far, instead of deleting certain rows, writerow deletes everything in the file. Could someone help me to understand how to fix it?
import csv
import os
import time
archive = os.listdir()
def get_user_files(self):
while True:
for position, file_name in enumerate(archive):
print(position, "-", file_name)
userInput = input("\n\n ")
if (int(userInput) < 0) or (int(userInput) > len(archive)):
print("Invalid Input. Try again. \n")
else:
print("Loading succesful!")
break
global cvs_list
cvs_list = archive[int(userInput)] # Store file
archive.remove(cvs_list) # Remove from the list
with open(cvs_list, 'r') as in_file, open(cvs_list, 'w') as out_file:
reader = csv.reader(in_file)
writer = csv.writer(out_file)
for row in reader:
next(reader) #skip headers
if int(row[2]) < 2011:
writer.writerow(row)
Edit:
with open(cvs_list, 'r') as in_file:
csv_in = csv.reader(in_file, quoting=csv.QUOTE_ALL)
filtered_list = []
row1 = next(csv_in)
filtered_list.append(row1)
for row in csv_in:
if int(row[2]) >= 2011:
row.append(filtered_list)
with open(cvs_list, 'w') as out_file:
writer = csv.writer(out_file)
writer.writerows(filtered_list)