การแยกไฟล์บีบอัดจากนามสกุล. gz ขณะที่ดาวน์โหลดจากเซิร์ฟเวอร์ ftp [ซ้ำกัน]

Aug 20 2020

ฉันได้สร้างฟังก์ชั่นที่ดาวน์โหลดไฟล์. gz จากเซิร์ฟเวอร์ ftp ที่กำหนดและฉันต้องการแยกไฟล์เหล่านี้ทันทีในขณะที่ดาวน์โหลดและลบไฟล์บีบอัดในภายหลัง ฉันจะทำเช่นนั้นได้อย่างไร?

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()ไม่จำเป็นต้องใช้)