I'm having a problem writing my text to an excel sheet:
Here's my code:
import xlwt
wbk = xlwt.Workbook()
sheet = wbk.add_sheet('python')
row = 0 # row counter
col = 0
f = open('newfile.txt')
for line in f:
L = line.split('\t')
for c in L:
sheet.write(row,col,c)
row += 1
wbk.save('example12.xls')
And here's input.txt
:
Ename DCname Competency Effort
Eng01 DC1 SW 30
Eng02 DC2 HW 30
Eng03 DC3 ME 40
Eng04 DC2 SW 20
Eng05 DC3 FW 40
Eng06 DC3 SW 35
Eng07 DC1 HW 25
Eng08 DC3 SW 30
Eng09 DC1 HW 35
Eng10 DC3 SW 20
Eng11 DC1 HW 40
Eng12 DC3 SW 40
Eng13 DC1 HW 30
Eng14 DC1 HW 30
Eng15 DC3 FW 40
But input.txt is writing into only one column, how can I get it to write into different columns?
Your problem is here:
for line in f:
L = line.split('\t')
for c in L:
sheet.write(row,col,c)
row += 1
col
never gets changed from 0
so it always writes to the same column. You could be incrementing it during that loop, but it's better to use enumerate
. enumerate
returns the index of each iteration of a loop, so you can count which number column you're on with it. Like this:
for line in f:
L = line.split('\t')
for i,c in enumerate(L):
sheet.write(row,i,c)
row += 1
i
is the number of the column found in the line so it will write each piece of data out to the next column.