lhcgeneva lhcgeneva - 13 days ago 6x
Python Question

Automate conversion txt to xls

I am looking for the cheapest way of automating the conversion of all the text files (tab-delimited) in a folder structure into .xls format, keeping the shape of columns and rows as it is.

Currently I am on MacOS. Linux and Windows are available though.


import xlwt
import xlrd
f = open('Text.txt', 'r+')
row_list = []
for row in f:
column_list = zip(*row_list)
workbook = xlwt.Workbook()
worksheet = workbook.add_sheet('Sheet1')
i = 0
for column in column_list:
for item in range(len(column)):
worksheet.write(item, i, column[item])

This should do...


The easiest way would be to just rename all of the files from *.txt to *.xls. Excel will automatically partition the data, keeping the original shape.

I'm not going to write your code for you, but here is a head start:

  • You can list a directories contents using os.listdir()
  • You can use os.path.isdir() and os.path.isfile() to see if each 'thing' you just found in your intial directory is a file or a directory, and act on accordingly
  • You can use os.rename() to rename a file and os.remove() to delete a file
  • You can use os.path.splitext() to split the files name and extension, or just file.endswith('.txt') to work on only the correct files