Automate conversion txt to xls

2020-07-13 09:31发布

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

2条回答
Root(大扎)
2楼-- · 2020-07-13 09:55

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
查看更多
三岁会撩人
3楼-- · 2020-07-13 09:58

How about this?

import xlwt
textfile = "C:/Users/your_path_here/Desktop/test.txt"

def is_number(s):
    try:
        float(s)
        return True
    except ValueError:
        return False        


style = xlwt.XFStyle()
style.num_format_str = '#,###0.00'  

#for textfile in textfiles:
f = open(textfile, '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)):
        value = column[item].strip()
        if is_number(value):
            worksheet.write(item, i, float(value), style=style)
        else:
            worksheet.write(item, i, value)
    i+=1
workbook.save(textfile.replace('.txt', '.xls'))

Sorry, must have pasted in the wrong thing...

查看更多
登录 后发表回答