Search code examples
excelpython-2.7csvxlrdxlwt

Appending data when writing from excel sheet to txt document


There is a text document called: file.txt with text already on it.

When I go through the excel sheet and write to the text file it erases the original text on it.

How do I only append the info from the excel sheet while keeping the original text info?

CODE

import xlwt
import xlrd
import csv

workbook = xlrd.open_workbook('input.xls')
sheet = workbook.sheet_by_index(2)

data = []
data.append([sheet.cell_value(row, 0).strip() for row in range(sheet.nrows)])
data.append([sheet.cell_value(row, 1).strip() for row in range(sheet.nrows)])

workbook = xlwt.Workbook()
sheet = workbook.add_sheet('test')

for colidx, col in enumerate(data):
    for rowidx, row in enumerate(col):
        sheet.write(rowidx, colidx, row)    

transposed = zip(*data)
with open('file.txt','wb') as fou:
    writer = csv.writer(fou)
    for row in transposed:
        writer.writerow(row)

Solution

  • If I understand correctly you want to pass ab as a flag to open():

    transposed = zip(*data)
    #                     v
    with open('file.txt','ab') as fou:
        writer = csv.writer(fou)
        for row in transposed:
            writer.writerow(row)