-2

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.

MattDMo
  • 100,794
  • 21
  • 241
  • 231
Praveenks
  • 1,436
  • 9
  • 40
  • 79

3 Answers3

1

You can use enumerate():

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

It would basically make pairs of a current index and a sequence item. By default, starting with 0:

>>> l = ['a', 'b', 'c']
>>> for index, item in enumerate(l):
...     print index, item
... 
0 a
1 b
2 c
alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
1

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.

MattDMo
  • 100,794
  • 21
  • 241
  • 231
1

The function called enumerate() is what you need, this function calls index numbers of each element and the element. A quick example;

>>> a=["x","y","z"]
>>> for h,y in enumerate(a):
    print (h,y)


0 x
1 y
2 z
>>> 

So you should use this one;

for index, direc in enumerate(os.listdir("F:\\")): #you can write whatever you want
    sheet.write(index, 0, direc)                 #instead of index and direc
                                                #but be sure you don't store them
                                               #as variables before
GLHF
  • 3,835
  • 10
  • 38
  • 83