Python Forum
copy content of text file with three delimiter into excel sheet - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: copy content of text file with three delimiter into excel sheet (/thread-28281.html)



copy content of text file with three delimiter into excel sheet - vinaykumar - Jul-12-2020

I have a text file n numbers of rows and columns separated by three delimiters [ , ], - .
I need to import this into excel using python.

sample data of my text file is:

AM[38070] 22220-22-0-0-0-0-1-126-0-0-1-0-0-255-0
AM[38070] 22-0-0-1-1-126-0-0-0-126-0-4095-2047-2047-1
Note there are n numbers of rows and columns i need to write all into excel file

I have tried below code but it only takes one delimiter in consideration

I am not sure what to use instead of row = data[i].split('[')

Below is my code
# mypath should be the complete path for the directory containing the input text files
mypath = raw_input("Please enter the directory path for the input files: ")

from os import listdir
from os.path import isfile, join
textfiles = [ join(mypath,f) for f in listdir(mypath) if isfile(join(mypath,f)) and '.txt' in  f]

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

import xlwt
import xlrd

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

for textfile in textfiles:
    f = open(textfile, 'r+')
    book = xlwt.Workbook()
    ws = book.add_sheet('First Sheet')  # Add a sheet
    data = f.readlines()  # read all lines at once
    for i in range(len(data)):
        row = data[i].split('[')

        for j in range(len(row)):
            ws.write(i, j, row[j])  # Write to cell i, j

        i+=1
    book.save(textfile.replace('.txt', '.xls'))
    f.close()