Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automate conversion txt to xls

Tags:

python

text

excel

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.

Edit: this did the trick:

import xlwt
import xlrd
f = open('Text.txt', 'r+')
row_list = []
for row in f:
    row_list.append(row.split())
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])
    workbook.save('Excel.xls')
    i+=1
like image 696
lhcgeneva Avatar asked Nov 03 '22 23:11

lhcgeneva


1 Answers

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
like image 93
Gareth Webber Avatar answered Nov 09 '22 04:11

Gareth Webber