ftp 서버에서 다운로드하는 동안 .gz 확장자에서 압축 파일 추출 [중복]
Aug 20 2020
주어진 ftp 서버에서 .gz 파일을 다운로드하는 기능을 만들었고 나중에 압축 파일을 다운로드하고 삭제하는 동안 즉시 추출하고 싶습니다. 어떻게 할 수 있습니까?
sinex_domain = "ftp://cddis.gsfc.nasa.gov/gnss/products/bias/2013"
def download(sinex_domain):
user = getpass.getuser()
sinex_parse = urlparse(sinex_domain)
sinex_connetion = FTP(sinex_parse.netloc)
sinex_connetion.login()
sinex_connetion.cwd(sinex_parse.path)
sinex_files = sinex_connetion.nlst()
sinex_userpath = "C:\\Users\\" + user + "\\DCBviz\\sinex"
pathlib.Path(sinex_userpath).mkdir(parents=True, exist_ok=True)
for fileName in sinex_files:
local_filename = os.path.join(sinex_userpath, fileName)
file = open(local_filename, 'wb')
sinex_connetion.retrbinary('RETR '+ fileName, file.write, 1024)
#want to extract files in this loop
file.close()
sinex_connetion.quit()
download(sinex_domain)
답변
1 alani Aug 20 2020 at 02:09
각 파일에 대해 전체 데이터를 메모리에 저장하지 않는 더 영리한 방법이있을 수 있지만 이러한 파일은 매우 작은 파일 (압축되지 않은 수십 킬로바이트) 인 것처럼 보이므로 압축 된 데이터를 BytesIO버퍼 로 읽어도 충분합니다. 출력 파일에 쓰기 전에 메모리에서 압축을 풉니 다. (압축 된 데이터는 디스크에 저장되지 않습니다.)
다음 가져 오기를 추가합니다.
import gzip
from io import BytesIO
그리고 메인 루프는 다음과 같습니다.
for fileName in sinex_files:
local_filename = os.path.join(sinex_userpath, fileName)
if local_filename.endswith('.gz'):
local_filename = local_filename[:-3]
data = BytesIO()
sinex_connetion.retrbinary('RETR '+ fileName, data.write, 1024)
data.seek(0)
uncompressed = gzip.decompress(data.read())
with open(local_filename, 'wb') as file:
file.write(uncompressed)
( file.close()이 필요하지 않습니다.)