AttributeError: 'list' object has no attribute 'endswith'

AttributeError: 'list' object has no attribute 'endswith'

我正在尝试访问给定文件夹,然后访问其所有子文件夹 (20+),然后访问每个子文件夹中唯一的 xlsx 文件以进行一些计算。

我的代码使用 openpyxl 中的 load_workbook。我需要一个 for 循环来读取同一文件夹中的现有文件,但这些文件的名称从子文件夹更改为子文件夹。为了解决 load_workbookxlsx 文件的精确名称作为输入这一事实,我选择了这个解决方案:

filename=os.path.basename(file)
wb=load_workbook(filename)

但它引发了这个错误:AttributeError: 'list' object has no attribute 'endswith'如何解决我的解决方法?

我的完整脚本:

import os
from openpyxl import load_workbook

directoryPath=r'C:\Users\MyName\Desktop\MyFolder'
os.chdir(directoryPath)
folder_list=os.listdir(directoryPath)
for folders, sub_folders, file in os.walk(directoryPath):
    for name in file:
        if file.endswith(".xlsx"):
            filename=os.path.basename(file) #This is supposed to dump the name of the current file to a variable to be used by load_workbook
            wb=load_workbook(filename)
            cell_range = wb['A1':'A10'] #Accessing some cells

            #some calculations

改变

if file.endswith(".xlsx"):

if name.endswith(".xlsx"):