AttributeError:'list'对象没有属性'endswith'

FaC*_*fee 2 python directory filenames subdirectory

我试图访问给定的文件夹,然后访问其所有子文件夹(20+),然后访问xlsx每个子文件夹内的唯一文件进行一些计算.

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

filename=os.path.basename(file)
wb=load_workbook(filename)
Run Code Online (Sandbox Code Playgroud)

但它引发了这个错误: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
Run Code Online (Sandbox Code Playgroud)

Mar*_*nek 11

更改

if file.endswith(".xlsx"):

if name.endswith(".xlsx"):