Python:文本文件转Excel文件
我想用Python从我的桌面读取一个文本文件,然后把它写入一个Excel文件。
但是我遇到了一个错误:
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
这是我的代码:
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()
1 个回答
0
我想我找到了问题的解决办法。
问题出在我使用的分割函数的参数上,也就是
split_Line = space_remove.split(" ")
应该是这样的
split_Line = space_remove.split(",")
分割函数需要用(,)来正确地进行分割。
感谢所有试图帮助我的人。再见。