Delete rungs from a Python csv

1

With the following code I convert an XLSX into CSV. I need to delete the first 10 lines of the resulting csv. How could I do it?

# encoding=utf8
import sys
import xlrd
import csv

reload(sys)
sys.setdefaultencoding('utf8')


def csv_from_excel():
    wb = xlrd.open_workbook('excel.xlsx')
    sh = wb.sheet_by_name('Sheet1')
    your_csv_file = open('your_csv_file.csv', 'w')
    wr = csv.writer(your_csv_file, quoting=csv.QUOTE_ALL)

    for rownum in range(sh.nrows):
        wr.writerow(sh.row_values(rownum))

    your_csv_file.close()

# runs the csv_from_excel function:
csv_from_excel()
    
asked by Martin Bouhier 20.12.2017 в 18:17
source

1 answer

1

Instead of deleting just do not save the rows you do not want in the csv. just use range appropriately for it. To ignore the first 10 rows, simply:

for rownum in range(10, sh.nrows):
    wr.writerow(sh.row_values(rownum))

If the first row of your xlsx was actually the header and you want it to be passed to the csv, you can do:

wr.writerow(sh.row_values(0))
for rownum in range(11, sh.nrows):
    wr.writerow(sh.row_values(rownum))
    
answered by 20.12.2017 / 19:39
source