如何删除csv文件中的标题行?

时间:2017-05-27 14:16:40

标签: python python-3.x csv

我正在尝试制作库存跟踪器或项跟踪器程序。在set_header_row()方法下面,我希望用户能够在需要时替换标头。但我不知道如何删除标题。我一直在寻找一个类似的东西的解决方案,但我无法找到答案。如果需要进一步说明,请告诉我。

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()

1 个答案:

答案 0 :(得分:0)

尝试一下:

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)