nik
nik

Reputation: 2584

how to convert xlsx to tab delimited files

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

Upvotes: 2

Views: 12214

Answers (2)

Rukshan Ur Rahman
Rukshan Ur Rahman

Reputation: 11

Why go with so much pain when you can do it in 3 lines:

import pandas as pd

file = pd.read_excel('myfile.xlsx')

file.to_csv('myfile.xlsx',
             sep="\t",
             index=False)

Upvotes: 1

OneCricketeer
OneCricketeer

Reputation: 191743

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

Upvotes: 2

Related Questions