2

I have set up the following directory:

+---main
|   |   
|   +---sub1
|   |       file1.xlsx
|   | 
|   +---sub2
|   |       file2.xlsx
|   |
|   \---sub3
|           file3.xlsx

I want to access each file and compute the mean value of its A1:A10 cells, but while file1.xlsx exists, I get this error:

IOError: [Errno 2] No such file or directory: 'file1.xlsx'

My code as of now (it is designed to iterate over many "main" directories):

import os
from openpyxl import load_workbook

directoryPath=r'C:\Users\MyName\Desktop\MainFolder'
os.chdir(directoryPath)
folder_list=os.listdir(directoryPath)
for folders, sub_folders, file in os.walk(directoryPath):
    for name in file:
        if name.endswith(".xlsx"):
            filename=os.path.basename(name)
            wb=load_workbook(filename)
            cell_range = wb['A1':'A10']

            #computing the mean value

The error points at wb=load_workbook(filename). Why do I get it and how to fix it?

1 Answer 1

4

Please check documentation for os.walk. It states:

To get a full path (which begins with top) to a file or directory in dirpath, do os.path.join(dirpath, name).

It means the correct code should look like:

for folder, sub_folders, files in os.walk(directoryPath):
    for name in files:
        if name.endswith(".xlsx"):
            filename = os.path.join(folder, name)
            wb = load_workbook(filename)
            # ...
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.