如何使用python减小文件的大小?

如何使用python减小文件的大小?,python,compression,txt,Python,Compression,Txt,我想减少一个相当大的文件大小约350mb到一个小得多的文件如60mb,我需要减少一个文本文件的大小,任何减少文件大小的方法都是好的,过程必须是可逆的。。。请帮我这个代码可能会帮到你 import tarfile from tqdm import tqdm 压缩 def compress(tar_file, members): """ Adds files (`members`) to a tar_file and compress it &

我想减少一个相当大的文件大小约350mb到一个小得多的文件如60mb,我需要减少一个文本文件的大小,任何减少文件大小的方法都是好的,过程必须是可逆的。。。请帮我这个代码可能会帮到你

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()

让文件变小被称为,检查所有这些代码示例:标准库有gzip和zipfile模块。您可能有兴趣检查为什么要问我们如何用Python压缩文件?为什么没有现有的资源为你工作?你知道压缩吗?或者这是一个家庭作业?请不要通过破坏你的帖子为别人做更多的工作。通过在Stack Exchange网络上发布,您已授予Stack Exchange在a项下分发该内容的不可撤销权利,即无论您未来的选择如何。根据堆栈交换策略,帖子的非破坏版本是分发的版本。因此,任何故意破坏行为都将恢复原状。如果您想了解有关删除帖子的更多信息,请参阅: