Search code examples
pythonxlwt

Write in Excel using xlwt


I am trying to list out all the directories in my F: drive and write the names into excel.

For this I am using Python and xlwt.

I am getting some error while writing the names of the file in the excel.I tried to use for loop to increase row number but it is not working because it hits the same cell again while writing the second value.

Error:

Exception: Attempt to overwrite cell: sheetname=u'F_Directories' rowx=1 colx=0
import xlwt
import os

workbook = xlwt.Workbook()

sheet = workbook.add_sheet("F_Directories")

for dir in os.listdir("F:\\"):
# <--- Not sure how to increase row number (r)----> 
        sheet.write(r,0,dir)

workbook.save("C:\\Users\\praveen\\Desktop\\OnlinePayment_files\\Stuffs.xls")

Please suggest.


Solution

  • This is a good case for enumerate:

    for r, dir in enumerate(os.listdir("F:\\")):
        sheet.write(r, 0, dir)
    

    enumerate is like adding the range function to an iterator - it starts at 0, and adds 1 with every iteration through the loop.