如何解决从.gz扩展名中提取压缩文件,同时从ftp服务器下载压缩文件
我创建了一个功能,可以从给定的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)
解决方法
虽然可能有一种更聪明的方法来避免将每个文件的整个数据存储在内存中,但这些文件似乎是很小的文件(未压缩的几十千字节),因此将压缩后的数据读入一个文件就足够了。 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()
。)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。