Python/Excel - IOError : [Errno 2] No such file or directory:

标签 python excel xlrd xlsxwriter

尝试从文件中提取 .xlsx 文档并将数据编译到单个工作表中。

尽管文件存在,但仍收到 IOError

程序如下

#-------------- loop that pulls in files from folder--------------
import os

#create directory from which to pull the files
rootdir = r'C:\Users\username\Desktop\Mults'

for subdir, dir, files in os.walk(rootdir):
for file in files:
    print os.path.join(subdir,file)
#----------------------merge work books-----------------------

import xlrd
import xlsxwriter


wb = xlsxwriter.Workbook('merged.xls')
ws = wb.add_worksheet()
for file in files:
    r = xlrd.open_workbook(file)
    head, tail = os.path.split(file)
    count = 0
    for sheet in r:
        if sheet.number_of_rows()>0:
            count += 1
    for sheet in r:
        if sheet.number_of_rosw()>0:
            if count == 1:
                sheet_name = tail
            else:
                sheet_name = "%s_%s" (tail, sheet.name)
            new_sheet = wb.create_sheet(sheet_name)
            new_sheet.write_reader(sheet)
            new_sheet.close()
wb.close()

返回错误如下

doc1.xlsx
doc2.xlsx
doc3.xlsx
doc4.xlsx

Traceback (most recent call last):
  File "C:\Users\username\Desktop\Work\Python\excel practice\xlsx - loops files - 09204.py", line 23, in <module>
    r = xlrd.open_workbook(file)
  File "C:\Python27\lib\site-packages\xlrd\__init__.py", line 394, in open_workbook
    f = open(filename, "rb")
IOError: [Errno 2] No such file or directory: 'doc1.xlsx'

有什么建议或改变吗?

此外,如果我朝着正确的方向前进,有什么建议吗?

我是Python世界的新手,所以任何建议将不胜感激!

谢谢!!

最佳答案

您正在打开不带路径的纯文件名;您忽略了目录组件。

不要只打印 os.path.join() 结果,实际使用它:

filename = os.path.join(subdir, file) 
r = xlrd.open_workbook(filename)

关于Python/Excel - IOError : [Errno 2] No such file or directory:,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26109374/

相关文章:

python - 与 SQLAlchemy 中列的切片和转换值的关系

excel - 在某些条件下求和

excel - Ctrl-End 不会将我带到最后一个单元格

Python xlwt - 访问现有单元格内容,自动调整列宽

python - 如何使用 Python 将一行 Excel 工作表复制到另一个工作表

python - 使用 PySNMP 作为自有/供应商 MIB 的陷阱接收器

python - 如何使用pycharm professional在behave中运行多个特征文件

python - 如何使用 Python 2 和 Python 3 中的内置库 ElementTree 等实体解析 HTML?

excel - 用 Cribbage 手数对

python - 在Python中从Excel工作表中查找值