将给定的较大文件缩小到 python 中的特定文件大小

Reduce a given larger file to specific file size in python

出于测试目的,我正在尝试将较大的文件缩小到给定的文件大小。代码如下:

f = open ('original_file', 'rb')
f.seek(1000000)
rest = f.read()
f.close()
f1 = open('new_file', 'w')
f1.write(rest)
f1.close()

无论内容如何,​​我都想从该文件中减少 1 MB。但是我无法在同一个文件中减少。请帮助我出错的地方或任何其他方法将同一文件的内容减少到指定的 MB。谢谢

要trim一个文件到确定的大小,保持其开头,可以使用os.truncate调用。

您没有提及是否要在文件的开头或结尾剃除字节 - 但从您的代码中可以推断出它在开头。

在那种情况下,由于在某些 file-systens 中可以使用常见的 truncate 调用来在文件末尾剪辑文件,因此需要做的就是将数据从所需位置写入到在文件的开头结束。一种紧凑的方法是简单地打开文件两次 - (在某些 O.S.s 中可能不起作用,只需将 dta 读取到临时对象,然后再次打开文件进行写入,在这种情况下):

import os

def truncate_begining(path, length):
    """Remove length bytes at the beggning of given file"""
    original_length = os.stat(path).st_size
    with open(path, "r+b") as reading, open(path, "r+b") as writting:
        reading.seek(length)
        writting.write(reading.read())
    try:
        os.truncate(path, orginal_length - length)
    except OSError as error:
        print("Unable to truncate the file:", error)

请注意,truncate 功能并非在所有情况下都可用,这取决于文件所在的文件系统是否具有此功能。如果没有,调用 truncate 将引发错误。 (文档说这个调用是 Python 3.3 中的新调用,并且仅在 Python 3.5 之后才可用于 Windows)

对于Python 3.3之前的版本,在Linux上,可以利用ctypes直接调用系统的truncate:

import ctypes
libc = ctypes.CDLL("libc.so.6")
libc.truncate(<path>, <length>)