Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
587 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 Reply

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...