2014-09-29 2 views
1

파일에서 .xlsx 문서를 추출하고 데이터를 단일 워크 시트로 컴파일하려고합니다.Python/Excel - IOError : [Errno 2] 해당 파일이나 디렉토리가 없습니다.

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' 

어떤 제안 또는 변경 내용을 다음과 같이

#-------------- 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() 

반환 오류를 다음과 같이 파일이 존재

프로그램에도 불구하고 IO 오류를 받기

은?

또한 올바른 방향으로 나아가고 있다면 조언을 드리겠습니다.

저는 파이썬 세계에 처음 왔으므로 어떤 조언도 많이 부탁드립니다!

감사합니다.

답변

2

경로없이 일반 파일 이름을 여는 중입니다. 디렉토리 구성 요소를 무시합니다.

그냥 os.path.join() 결과를 출력하지 않는다, 실제로 그것을 사용 : 첫 번째 문제의 경우

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

내가 제공 한 구문으로 인쇄 구문을 바꾸는 것이 좋습니다. –

+0

@MikeV :'xlrd.open_workbook()'호출을 내가 준 코드로 대체 할 것을 제안합니다. –

+0

감사합니다. 그래서 그것을 대체했습니다 이제 r에 시트에 대한이 오류가 나타납니다 : TypeError : 'Book'개체를 iterable 수 없습니다. –

0

...

대신 :

r = xlrd.open_workbook(file) 

사용 :

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

유형 오류 : 대신 :

사용 :

for nsheet in r.sheet_names() #you need a list of sheet names to loop throug 
    sheet = r.sheet_by_name(nsheet) #then you create a sheet object with each name in the list 
    if sheet.nrows>0: #use the property nrows of the sheet object to count the number of rows 
     count += 1 

루프에 대한 두 번째에 동일한 작업을 수행합니다.

관련 문제