I am trying to make a Inventory tracker or Item tracker program. Below in the set_header_row()
method, I want the user to be able to replace the header if they want. But I don't know how to remove just the header. I have been searching for a solution to do something similar but I couldn't find away. If further clarification is needed please let me know.
import csv
class Product:
def __init__(self, file, mode):
self.f = file
self.m = mode
self.product_list = None
self.l = None
def open_file(self):
"""This class was made to be used within the class itself
This method is used to open a file specified and mode
It stores it in a variable and returns it to be used"""
try:
self.product_list = open(self.f, self.m)
print("File open successfully!")
print("File opened: " + str(self.f) + "\nMode: " + str(self.m))
return self.product_list
except FileNotFoundError:
print("The file you have specified does not exist.")
except PermissionError:
print("You do not have the adequate permissions to access: ", self.f)
def read_file(self):
try:
with self.open_file() as self.product_list:
r = self.product_list.read()
print(r)
except ValueError:
print("Value Error")
def get_header_row(self):
head_row_reader = csv.reader(self.product_list)
head_row = ''
for row in head_row_reader:
head_row += str(row)
break
return head_row
def set_header_row(self, heading_row):
try:
with self.open_file() as self.product_list:
w = csv.writer(self.product_list)
l = self.get_header_row()
if l == '':
w.writerow(heading_row)
elif l != '':
erase_header = input("The header is not empty. Do you want to replace it?(Y/N)")
if erase_header in ("y", "Y"):
self.l = ''
w.writerow(heading_row)
print("Header has been replaced.")
elif erase_header in ('n', 'N'):
print("The header currently is: ", l)
self.product_list.close()
except IOError:
print("Error")
p = Product("data.csv", "r+")
p.open_file()
p.set_header_row(['test1', 'test2'])
p.read_file()