how to convert xlsx to tab delimited files

nik picture nik · Dec 18, 2016 · Viewed 8.9k times · Source

I have quite a lot of xlsx files which is a pain to convert them one by one to tab delimited files

I would like to know if there is any solution to do this by python. Here what I found and what tried to do with failure This I found and I tried the solution but did not work Mass Convert .xls and .xlsx to .txt (Tab Delimited) on a Mac

I also tried to do it for one file to see how it works but with no success

#!/usr/bin/python
import xlrd
import csv


def main():
    # I open the xlsx file 
    myfile = xlrd.open_workbook('myfile.xlsx')
    # I don't know the name of sheet
    mysheet = myfile.sheet_by_index(0)
    # I open the output csv
    myCsvfile = open('my.csv', 'wb')
    # I write the file into it
    wr = csv.writer(myCsvfile, delimiter="\t")
    for rownum in xrange(mysheet.nrows):
        wr.writerow(mysheet.row_values(rownum))
    myCsvfile.close()
if __name__ == '__main__':
   main()

Answer

OneCricketeer picture OneCricketeer · Dec 18, 2016

No real need for the main function.

And not sure about your indentation problems, but this is how I would write what you have. (And should work, according to first comment above)

#!/usr/bin/python
import xlrd
import csv

# open the output csv
with open('my.csv', 'wb') as myCsvfile:
    # define a writer
    wr = csv.writer(myCsvfile, delimiter="\t")

    # open the xlsx file 
    myfile = xlrd.open_workbook('myfile.xlsx')
    # get a sheet
    mysheet = myfile.sheet_by_index(0)

    # write the rows
    for rownum in xrange(mysheet.nrows):
        wr.writerow(mysheet.row_values(rownum))