Python/Excel-IOError:[Errno 2]没有这样的文件或目录: [英] Python/Excel - IOError: [Errno 2] No such file or directory:
本文介绍了Python/Excel-IOError:[Errno 2]没有这样的文件或目录:的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
尝试从文件中提取.xlsx文档,并将数据编译到单个工作表中.
Attempting to extract .xlsx docs from a file and compile the data into a single worksheet.
尽管文件存在也接收到IOError
Receiving a IOError despite that the files exist
程序如下
#-------------- 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'
有什么建议或改变吗?
如果我朝着正确的方向前进,还有什么建议吗?
Also, any advice if I'm heading in the right direction?
我是python世界的新手,所以任何建议都将不胜感激!
I'm new to the python world, so any advice will be much appreciated!
谢谢!
推荐答案
您正在打开不带路径的纯文件名;您将忽略目录组件.
You are opening the plain filename without the path; you are ignoring the directory component.
不仅仅是打印 os.path.join()
结果,而是实际使用它:
Don't just print the os.path.join()
result, actually use it:
filename = os.path.join(subdir, file)
r = xlrd.open_workbook(filename)
这篇关于Python/Excel-IOError:[Errno 2]没有这样的文件或目录:的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文