【问题标题】:how do i reduce the size of a file using python?如何使用 python 减小文件的大小?
【发布时间】:2021-04-06 09:03:37
【问题描述】:

我想将一个相当大的文件(大约 350mb)的大小减小到一个小得多的文件,例如(60mb),我需要减小一个文本文件的大小,任何减小文件大小的方法都可以,过程必须是可逆的......请帮助我

【问题讨论】:

  • “使文件更小”被称为compression,查看所有这些代码示例:google.com/…
  • 标准库有 gzip 和 zipfile 模块。
  • 您可能有兴趣查看How to compress a large file in Python?
  • 为什么要问我们如何在 Python 中压缩文件?为什么没有现有资源对您有用?你知道压缩吗?还是这是家庭作业?

标签: python compression txt


【解决方案1】:

此代码可能会对您有所帮助..

import tarfile
from tqdm import tqdm

压缩

def compress(tar_file, members):
    """
    Adds files (`members`) to a tar_file and compress it
    """
    # open file for gzip compressed writing
    tar = tarfile.open(tar_file, mode="w:gz")
    # with progress bar
    # set the progress bar
    progress = tqdm(members)
    for member in progress:
        # add file/folder/link to the tar file (compress)
        tar.add(member)
        # set the progress description of the progress bar
        progress.set_description(f"Compressing {member}")
    # close the file
    tar.close()

解压

def decompress(tar_file, path, members=None):
    """
    Extracts `tar_file` and puts the `members` to `path`.
    If members is None, all members on `tar_file` will be extracted.
    """
    tar = tarfile.open(tar_file, mode="r:gz")
    if members is None:
        members = tar.getmembers()
    # with progress bar
    # set the progress bar
    progress = tqdm(members)
    for member in progress:
        tar.extract(member, path=path)
        # set the progress description of the progress bar
        progress.set_description(f"Extracting {member.name}")
    # or use this
    # tar.extractall(members=members, path=path)
    # close the file
    tar.close()

【讨论】:

  • 请不要通过破坏您的帖子为他人增加工作量。通过在 Stack Exchange 网络上发布,您已授予不可撤销的权利,在 CC BY-SA license (2.5/3.0/4.0) 下,Stack Exchange 可以分发该内容(即无论您未来的选择如何)。根据 Stack Exchange 政策,帖子的非破坏版本是分发的版本。因此,任何破坏行为都将被撤销。如果您想了解更多关于删除帖子的信息,请参阅:How does deleting work?
猜你喜欢
  • 1970-01-01
  • 2015-12-20
  • 2010-10-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多