简体   繁体   中英

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:\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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM