为什么变量有效,但在 python 中使用 xlrd 打开工作簿的列表无效?

Why does a variable work, but not a list for opening a workbook using xlrd in python?

我是 python 的新手,非常感谢您的帮助。在过去的 4 天里,我一直在从我能想象到的各个角度来解决这个问题,希望我能自己弄明白,但我被难住了。

我正在尝试从扩展名为 .xlsx 的特定目录创建文件列表。然后我想从列表中获取这些文件名和 运行 一些函数,将发现的文件名传递给函数,并用每个文件名对其进行迭代。我尝试以多种方式执行此操作,但出于某种原因我不接受文件名。

import os
import xlrd

mypath = "some path to files"
fileslist = []

def find_files():
    for file in os.listdir(mypath):
        if file.endswith(".xlsx")
            fileslist.append(file)

def other_function():    
    book = xlrd.open_workbook(fileslist)

我可以打印文件列表并显示其中填充了正确的信息。我已经在脚本的主要部分和 other_function() 区域中完成了此操作。我还尝试测试在目录中使用有效文件名命名变量文件列表,假设 "file1.xlsx" 并且可行。一旦我将它输入到列表中,即使列表中的唯一条目是 "file1.xlsx" 我也会收到以下错误

book = xlrd.open_workbook(fileslist)
  File "/Library/Python/2.7/site-packages/xlrd/__init__.py", line 110, in open_workbook
    filename = os.path.expanduser(filename)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/posixpath.py", line 254, in expanduser
    if not path.startswith('~'):
AttributeError: 'list' object has no attribute 'startswith'

xlrd 正在寻找要打开的文件路径。 (文件)列表是 1) 不是文件路径,而是多个文件路径和 2) 不是字符串,这是您遇到的特定错误。一个字符串(它是一个 Python 对象)有一个方法 .startswith 允许 xlrd 检查文件路径的第一部分(你应该给 open_workbook)是 ~ 还是不是。 xlrd 可能这样做是因为这会影响它查找文件的位置。

xlrd.open_workbook 实质上是在尝试双击您发送的文件路径,您(实质上)是在尝试同时单击列表中的所有文件,如果您可以有 X 个不同的计算机鼠标,每个鼠标都有一只手,但计算机的通常构建方式实际上是不可能的。

如果你想为你拥有的不同工作簿制作一个字典,但是用 xlrd 打开你可以使用这个:

xlrd_wbs = dict()
for my_file in filelist:
    xlrd_wbs[my_file] = xlrd.open_workbook(my_file)

然后访问不同的文件:

xlrd_wbs[whatever_file_path_you_used]

我会在这里使用字典,因为它允许您更可靠地访问您想要的文件,如果您只想要一个列表,您可以这样做:

xlrd_wbs = []
for my_file in filelist:
    xlrd_wbs.append(xlrd.open_workbook(my_file))