I'm writing a program to write folder names&file names to Excel with python.
I get an error in the for statement and I don't know what caused it and where to fix it.

I created the code as below.
import os
import openpyx1

book = openpyx1.Workbook ()

sheet = book.active
sheet.title ='First sheet'

for folder, subfolders, files in os.walk ('AAA'):
a ='folder: {}'. format (folder)
for row in sheet:
for cell in row:
cell.value = a

book.save ('demo.xlsx')

When I do this, I get the following error:
TypeError! iter () returned non-iterator of type'tuple'

When I tried to execute the code line by line to see the cause in detail, an error occurred on the 9th line.

File "", line 1
for folder, subfolders, files in os.walk ('AAA'):
^ ^
SyntaxError: unexpected EOF while parsing

The same error as above occurs on lines 11 and 12.

On the 13th line, the following error occurs.
NameError! name'cell is not defind

If anyone knows, please give me a professor.

  • Answer # 1

    Since openpxl is written with openpx1 (the end is not ell but ichi), I can't think of the code that is running as it is (an error should occur there), but what do you want to do?

    import os
    import openpyxl
    book = openpyxl.Workbook ()
    sheet = book.active
    sheet.title ='First sheet'
    sheet ["A1"]. value = "Folder"
    sheet ["B1"]. value = "Subfolders"
    row = 2
    max_col = 1
    for folder, subfolders, files in os.walk ('ZZZ'):
        print (f'folder: {folder}, subfolders: {subfolders}, files: {files}')
        sheet.cell (row = row, column = 1) .value = str (folder)
        sheet.cell (row = row, column = 2) .value = "," .join (subfolders)
        col = 3
        for file in files:
            sheet.cell (row = row, column = col) .value = str (file)
            col + = 1
        if max_col<col:
            max_col = col
        row + = 1
    for i in range (3, max_col):
        sheet.cell (row = 1, column = i) .value = f "File {i}"
    book.save ('demo.xlsx')