How to write data from dat file into Excel in Python

Viewed 55

I would like to read data from .dat file inside a test sample folder (floats at A16 to C156)to take it to cells A16 to C156 in the first worksheet of an Excel workbook. I rename the first worksheet with the folder ID where data was taken.

Then repeat. Open the next folder, get the data, put in first worksheet, save as next worksheet.

How do I change this script to append worksheet to "MasterWorksheet" instead of creating new Excel files?

from win32com.client import Dispatch
import os
from glob import glob
import time
folder='C:\\Users\\cs3761\\Desktop\\Crunch\\'
excel = Dispatch('Excel.Application')
masterwb = excel.Workbooks.Open(os.path.join(folder,'MasterWorksheet.xlsx'))

def dat_to_xls(code):
    newFileName = folder+code+".xlsx"
    ws = masterwb.Sheets('Data')
    fi = open(folder+code+'\\specimen.dat', 'r')
    print ('Converting file ' + newFileName)
    lineCount = 1
    array = []
    for line in fi:
        newArray = ['','','']
        c = 0
        for item in line.replace('\n','').split('\t'):
            if c < 3:
                newArray[c] = item
                c+=1
        array.append(newArray)
        lineCount+=1
    ws.Range(ws.Cells(1,1),ws.Cells(lineCount,3)).Value = array
    masterwb.SaveAs(newFileName)


start_time = time.time()
#prefix for files
prefix = 'AID_0310130-35-CSS-'
#find all folders in directory
paths = [ p.replace('\\', '') for p in glob('*/') ]
for fo in paths:
    if prefix in fo:
        #int(fo.split('-')[1])
        dat_to_xls(fo)

masterwb.Close(False)
excel.Quit()

print("--- Program ran in %s seconds ---" % (time.time() - start_time))
0 Answers
Related