2014-07-18 6 views
1

zip 파일의 모든 .xls 파일을 식별하기 위해 네트워크 디렉토리를 반복적으로 검색하려고합니다. 파일 zip에있는 XLS 파일마다 로컬 위치 C:에 복사하고 싶습니다. 지금까지 내 스크립트는 다음과 같습니다.Python의 zipfile 내용 복사

import os 
import zipfile 
import fnmatch 
import shutil 

rootPath = "L:\Data\Cases" 
destPath = "C:\Test" 
allFileList = [] 
zipList = [] 

# Create a list containing all files contained within L:\Data\Cases 
for dirname, dirnames, filenames in os.walk(rootPath): 
    for filename in filenames: 
     allFileList.append(os.path.join(dirname, filename)) 

# Return a list of filepaths containing zipfiles. 
for file in allFileList: 
    if file.endswith(".zip"): 
     zipList.append(file) 

for file in zipList: 
    with zipfile.ZipFile(file) as zip_file: 
     for member in zip_file.namelist(): 
      if member.endswith(".xls"): 
       filename = os.path.basename(member) 
       if not filename: 
        continue 
       source = zip_file.open(member) 
       target = os.path.join(destPath, filename) 
       shutil.copy2(source, target) 

오류 코드는 다음과 같습니다. 나는 압축 된 컨테이너에있는 파일이 실제로 대상 경로에 복사 됨으로 인해 오류가 발생했다고 생각합니다.

Traceback (most recent call last): 
    File "C:/Users/user/Desktop/parsecsv.py", line 30, in <module> 
    shutil.copy2(source, target) 
    File "C:\Program Files\Python278\lib\shutil.py", line 130, in copy2 
    copyfile(src, dst) 
    File "C:\Program Files\Python278\lib\shutil.py", line 68, in copyfile 
    if _samefile(src, dst): 
    File "C:\Program Files\Python278\lib\shutil.py", line 63, in _samefile 
    return (os.path.normcase(os.path.abspath(src)) == 
    File "C:\Program Files\Python278\lib\ntpath.py", line 487, in abspath 
    path = _getfullpathname(path) 

의견이 있으십니까?

+0

'ROOTPATH ​​= "L : \ 데이터 \".?. '(큰 따옴표) 문자를 탈출 – Nilesh

+0

당신이 편집하고 오류를 표시 할 수 있습니다 그것은 도움이 될 –

+0

을 "마지막으로 할 약간의 변화로 편집하고 최신 오류 – thefragileomen

답변

2

나는 당신이 ZipFile에 내용을 확인할 수 없다고 생각하지만 난 깨끗한 방법을 따라서 추출 후에 제거 할 수 있다고 생각 -이 목록에 당신은뿐만 아니라 한 번에 모든 일을 할 수 shutil.rmtree를 사용하여 다른 것들을 제거 할 수 있습니다.

def main(): 
rootPath = "C:\\rootpath" 
destPath = "C:\\Test" 
allFileList = [] 
zipList = [] 
# Create a list containing all files contained within L:\Data\Cases 
for dirname, dirnames, filenames in os.walk(rootPath): 
    for filename in filenames: 
     allFileList.append(os.path.join(dirname, filename)) 

# Return a list of filepaths containing zipfiles. 
for file in allFileList: 
    if file.endswith(".zip"): 
     zipList.append(file) 


for file in zipList: 
    with zipfile.ZipFile(file) as zip_file: 
     for member in zip_file.namelist(): 
      if member.endswith(".xls"): 
       zip_file.extract(member, destPath) 

for dirname, dirnames, filenames in os.walk(destPath): 
    for filename in filenames: 
     if not filename.endswith(".xls"): 
      shutil.rmtree(filename) 

if __name__ == '__main__': 
main() 
2

ZipFile.open()은 파일 시스템 경로가 아니라 파일 형태의 ZipExtFile 개체를 반환합니다. 당신이 원하는 것은 ZipFile.extract() (그리고 당신은 모든 shutil.copy() 필요하지 않습니다) :

또한
# NB : untested code, refer to the doc for more infos 
for file in zipList: 
    with zipfile.ZipFile(file) as zip_file: 
     for member in zip_file.namelist(): 
      if member.endswith(".xls"): 
       zip_file.extract(member, destPath) 

및 FWIW, 당신은 다음 반복 한 후 ZipFile에의 목록을 작성 먼저 모든 파일의 목록을 구축 할 필요가 없습니다 브루노에 의해 언급 한 바와 같이

for dirname, dirnames, filenames in os.walk(rootPath): 
    for filename in filenames: 
     if not filename.endswith(".zip"): 
      continue 
     fullpath = os.path.join(dirname, filename)) 
     with zipfile.ZipFile(fullpath) as zip_file: 
      for member in zip_file.namelist(): 
       if member.endswith(".xls"): 
        zip_file.extract(member, destPath) 
+0

많은 도움을 줘서 @ 브루노. 위의 위대한 작품이지만 xls 파일을 포함하는 폴더 구조를 추출합니다. 어쨌든 단순히 폴더 구조없이 xls 파일을 추출 할 수 있습니까? 감사합니다 – thefragileomen

+0

직접 AFAICT. 상관 없으면 당신이'ZipFile.open()'을 사용하여 파일의 메타 데이터 (시간 등)에 대해 새로 생성 된 파일에 내용을 쓰면, 임시 대상에 파일을 먼저 추출한 다음'shutil.move() '그것은 목적지가 원하는 곳입니다. –