【问题标题】:Best (most "pythonic") way to temporarily unzip a file临时解压缩文件的最佳(最“pythonic”)方法
【发布时间】:2011-12-12 19:36:27
【问题描述】:

我需要临时创建一些文件的解压缩版本。我见过有人在 bash 中做zcat somefile.gz > /tmp/somefile,所以我在 python 中做了这个简单的函数:

from subprocess import check_call
def unzipto(zipfile, tmpfile):
    with open(tmpfile, 'wb') as tf:
        check_call(['zcat', zipfile], stdout=tf)

但使用 zcat 和 check_call 对我来说似乎很老套,我想知道是否有更多“pythonic”方式来做到这一点。

感谢您的帮助

【问题讨论】:

  • “暂时”是什么意思?你需要它做什么?

标签: gzip python


【解决方案1】:

gzip.open(zipfile).read() 将在单个字符串中为您提供文件的内容。

with open(tmpfile, "wb") as tmp:
    shutil.copyfileobj(gzip.open(zipfile), tmp)

会将内容放在一个临时文件中。

【讨论】:

  • 谢谢,这看起来更干净,运行更快。
  • 添加到这里,有一个 python 模块来处理创建和删除临时文件和目录 (docs.python.org/library/tempfile.html)。对这个案例很有帮助。
【解决方案2】:

您是否考虑过使用zlib 或gzip 或tarfile。

【讨论】:

  • +1。使用本机库可以为您提供许多灵活的选择。例如,您可以将数据解压到内存中,或者获取解压后的数据流并且从不将其存储在任何地方(这两种方法都可以完全避免临时文件的需要)。
  • 我尽量避免这种事情,但在这种情况下,没有办法创建临时文件。感谢您的意见。
猜你喜欢
  • 2014-11-09
  • 1970-01-01
  • 1970-01-01
  • 2021-01-13
  • 1970-01-01
  • 2010-11-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多