-3

I'm trying to read a text file from my desktop and write it into an Excel file using Python.

I get the error:

Traceback (most recent call last):
  File "C:\Users\Kenny\Desktop\TTUMExcel.py", line 26, in <module>
    worksheet.write(row, col + 1, split_Line[1])
IndexError: list index out of range

Here is my Code:

import os
import re
import xlsxwriter

path = 'C:\Users\Kenny\Desktop\TTUM 2'
listing = os.listdir(path)
workbook = xlsxwriter.Workbook("Bank Validation.xlsx")
bold = workbook.add_format({'bold' : True})
for infile in listing:
    dir_item_path = os.path.join(path, infile)
    fh = open(dir_item_path,'r')
    Fname = infile 
    Lname = Fname.split('.')[0]
    worksheet = workbook.add_worksheet(Lname)
    col = 0
    row = 0
    worksheet.write('A1', 'ACCOUNT', bold)
    worksheet.write('B1', 'COUNTRY', bold)
    worksheet.write('C1', 'DIGITS', bold)
    worksheet.write('D1', 'CORRECTIONBILLSTUFF', bold)
    for line in fh:
         space_remove = re.sub(r"\s+",",",line.rstrip())
         #Check for third argument of sub
         split_Line = space_remove.split(" ")
         worksheet.write(row, col, split_Line[0])
         worksheet.write(row, col + 1, split_Line[1])
         worksheet.write(row, col + 2, split_Line[2])
         worksheet.write(row, col + 3, split_Line[3])
         row += 1


    workbook.close()
halfer
  • 19,824
  • 17
  • 99
  • 186
Emack333
  • 660
  • 6
  • 11
  • Could you also post the complete error log? – sk11 Jul 17 '14 at 12:21
  • Post the error log to see what list is out of range? – Robert Jul 17 '14 at 12:22
  • Are you sure that the path does not contain any directories? If it contains any directory then `Lname = Fname.split('.')[0]` will complain. – sk11 Jul 17 '14 at 12:24
  • possible duplicate of [Python - Write to Excel Spreadsheet](http://stackoverflow.com/questions/13437727/python-write-to-excel-spreadsheet) – Pablo Stark Jul 17 '14 at 12:35
  • 1
    Think, i found the solution to it. The problem came from the argument used in the split function, i.e split_Line = space_remove.split(" ") it was supposed to be like this split_Line = space_remove.split(",") The split needed the (,) to split in the right way. Thanks to all of you who tried to help me. Bye. – Emack333 Jul 17 '14 at 15:17
  • I'm sorry i'm commenting on this question, i don't have enough rep yet to answer my question. – Emack333 Jul 17 '14 at 15:18

1 Answers1

0

Think, i found the solution to it. The problem came from the argument used in the split function, i.e

split_Line = space_remove.split(" ") 

it was supposed to be like this

split_Line = space_remove.split(",")

The split needed the (,) to split in the right way.

Thanks to all of you who tried to help me. Bye.

Emack333
  • 660
  • 6
  • 11