#!/usr/bin/python

"""
This script will convert an xlsx file to a tsv file.
Navigate to the folder with the files you'd like to convert,
the script will open all xlsx files and output tsv files
of the same name to the current folder.
"""

import xlrd  
import csv
import glob

# convert numbers to int, otherwise xlrd will add a decimal place
def num_to_int(cell):
    if cell.ctype == 2:
        return int(cell.value)
    else:
        return str(cell.value).replace("\n"," ")

# convert to list of lists
def get_rows(sheet):
    new_sheet = []
    for i_row in range(sheet.nrows):
        row = []
        for i_col in range(sheet.ncols):
            ce = sheet.cell(i_row,i_col)
            row.append(num_to_int(ce))
        new_sheet.append(row)
    return new_sheet


def main():

    infiles = glob.glob("*.xlsx")

    for file in infiles:
        # open and process workbook
        book = xlrd.open_workbook(file).sheet_by_index(0)
        rows = get_rows(book)

        # write to csv file
        outfile = f"{file.split('.xlsx')[0]}.tsv"
        with open(outfile, "w") as out_file:
            writer = csv.writer(out_file, delimiter = "\t", quoting=csv.QUOTE_ALL)
            writer.writerows(rows)

        print (f"{outfile} saved")

if __name__ == '__main__':
        main()