Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
581 views
in Technique[技术] by (71.8m points)

directory - Python: existing file not found (IOError: [Errno 2]) when using os.walk

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:UsersMyNameDesktopMainFolder'
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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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)
            # ...

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...