0

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()
martineau
  • 119,623
  • 25
  • 170
  • 301
Mr. Nobody
  • 23
  • 1
  • 5
  • You might find [this answer](https://stackoverflow.com/questions/11349333/when-processing-csv-data-how-do-i-ignore-the-first-line-of-data/11350095#11350095) helpful. If a csv has a header, you can skip over if with `next(csv_reader)`. – martineau May 27 '17 at 14:20
  • 1
    Or use the `csv.DictReader()` and `csv.DictWriter()` which will consume and write headers row. – AChampion May 27 '17 at 14:23
  • Off-topic: According to [PEP-8](https://www.python.org/dev/peps/pep-0008/#method-names-and-instance-variables) naming-conventions, you should use one leading underscore for non-public methods and instance variables. i.e. `def _open_file(self):`. This lets users of the class know that it is private and to avoid call it because it's an implementation detail and not part of the public interface to the class, – martineau May 27 '17 at 14:34
  • So instead of using `w = csv.writerow()` I used `w = csv.DictWriter()` and `w.writeheader()`. But is it possible to delete to former header. – Mr. Nobody May 27 '17 at 20:30
  • Why do you open the file multiple times? I believe you want to access the `csv header` like in a database. This is not possible. You have only the option to `write` or not to `write` a `header`. – stovfl May 28 '17 at 13:03
  • When you say that it's not possible, do you mean it's not possible in my code or not possible at all? – Mr. Nobody May 28 '17 at 19:39

1 Answers1

0

try this:

with open("review.csv",'+r')as csvfile:
  csvreader = csv.reader(csvfile) 
next(csvreader)
with open("updated.csv",'w') as f1:
     for line in csvfile:
        f1.write(line)
Tamil Selvan S
  • 562
  • 8
  • 25