2016-09-23 4 views
0

현재 gzip 파일 인 파이썬과 체크섬 중 하나 인 Python을 사용하여 두 개의 파일을 다운로드하려고합니다.gzipped 파일을 다운로드하고 md5 checksum it을 입력 한 다음 일치하는 경우 추출 된 데이터를 저장합니다.

gzipped 파일의 내용이 md5 체크섬과 일치하는지 확인한 다음 내용을 대상 디렉토리에 저장하고 싶습니다.

here 파일을 다운로드하는 방법을 알아 냈으며 체크섬을 계산하는 방법을 배웠습니다 here. JSON 구성 파일에서 URL을로드하고 JSON 파일 값을 구문 분석하는 방법을 배웠습니다 here.

다음 스크립트로 모두 넣었지만 gzipped 파일의 검증 된 내용을 저장하려고 시도했습니다. 당신의 md5Gzip에서

import json 
import gzip 
import urllib 
import hashlib 

# Function for creating an md5 checksum of a file 
def md5Gzip(fname): 
    hash_md5 = hashlib.md5() 

    with gzip.open(fname, 'rb') as f: 
     # Make an iterable of the file and divide into 4096 byte chunks 
     # The iteration ends when we hit an empty byte string (b"") 
     for chunk in iter(lambda: f.read(4096), b""): 
      # Update the MD5 hash with the chunk 
      hash_md5.update(chunk) 

    return hash_md5.hexdigest() 

# Open the configuration file in the current directory 
with open('./config.json') as configFile: 
    data = json.load(configFile) 

# Open the downloaded checksum file 
with open(urllib.urlretrieve(data['checksumUrl'])[0]) as checksumFile: 
    md5Checksum = checksumFile.read() 

# Open the downloaded db file and get it's md5 checksum via gzip.open 
fileMd5 = md5Gzip(urllib.urlretrieve(data['fileUrl'])[0]) 

if (fileMd5 == md5Checksum): 
    print 'Downloaded Correct File' 
    # save correct file 
else: 
    print 'Downloaded Incorrect File' 
    # do some error handling 
+0

, 단지 해시 대신'tuple'을 반환합니다. 즉, return hash_md5.digest(), file_content' –

답변

1

, 단지 해시 대신 tuple을 반환합니다.

def md5Gzip(fname): 
    hash_md5 = hashlib.md5() 
    file_content = None 

    with gzip.open(fname, 'rb') as f: 
     # Make an iterable of the file and divide into 4096 byte chunks 
     # The iteration ends when we hit an empty byte string (b"") 
     for chunk in iter(lambda: f.read(4096), b""): 
      # Update the MD5 hash with the chunk 
      hash_md5.update(chunk) 
     # get file content 
     f.seek(0) 
     file_content = f.read() 

    return hash_md5.hexdigest(), file_content 

그런 다음 코드에서 : 당신의`md5Gzip`에서

fileMd5, file_content = md5Gzip(urllib.urlretrieve(data['fileUrl'])[0])