我创建了一个函数,可以从给定的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)
虽然可能有一种更聪明的方法可以避免将每个文件的整个数据存储在内存中,但这些文件似乎非常小(未压缩的文件只有几十KB),因此将压缩数据读入
BytesIO
缓冲区,然后在将其写入输出文件之前在内存中解压缩就足够了。(压缩数据永远不会保存到磁盘。)您将添加以下导入:
然后你的主循环变成:
(请注意,
file.close()
是不需要的。)相关问题 更多 >
编程相关推荐