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
我想访问每个文件并计算其 A1:A10
单元格,但是存在 file1.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:[错误2]没有这样的文件或目录:'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
错误点位于 wb = load_workbook(filename)
。为什么我要获取它以及如何解决它?
The error points at wb=load_workbook(filename)
. Why do I get it and how to fix it?
推荐答案
请检查 os.walk
的文档。它指出:
Please check documentation for os.walk
. It states:
要获取目录路径中文件或目录的完整路径(从顶部开始),请执行os.path.join (目录路径,名称)。
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)
# ...
这篇关于Python:使用os.walk时找不到现有文件(IOError:[Errno 2])的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!