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()は必要ないことに注意してください。)