简体   繁体   English

Python:使用os.walk时找不到现有文件(IOError:[Errno 2])

[英]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: 我想访问每个文件并计算其A1:A10单元的平均值,但是当file1.xlsx存在时,出现此错误:

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) . 错误指向wb=load_workbook(filename) Why do I get it and how to fix it? 为什么得到它以及如何解决?

Please check documentation for os.walk . 请检查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). 要获取目录路径中文件或目录的完整路径(从顶部开始),请执行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)
            # ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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