Python,如何从文件中读取字节并保存?

2024-04-26 15:06:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我想从一个文件中读取字节,然后将这些字节写入另一个文件,并保存该文件。

我该怎么做?


Tags: 文件字节
3条回答
with open("input", "rb") as input:
    with open("output", "wb") as output:
        while True:
            data = input.read(1024)
            if data == "":
                break
            output.write(data)

上面的代码一次读取1千字节,然后写入。您可以通过这种方式支持非常大的文件,因为您不需要将整个文件读入内存。

下面是如何使用Python中的基本文件操作来实现这一点。这将打开一个文件,将数据读入内存,然后打开第二个文件并将其写出。

in_file = open("in-file", "rb") # opening for [r]eading as [b]inary
data = in_file.read() # if you only wanted to read 512 bytes, do .read(512)
in_file.close()

out_file = open("out-file", "wb") # open for [w]riting as [b]inary
out_file.write(data)
out_file.close()

通过使用with键盘来处理关闭文件,我们可以更简洁地完成此操作。

with open("in-file", "rb") as in_file, open("out-file", "wb") as out_file:
    out_file.write(in_file.read())

如果不想将整个文件存储在内存中,可以将其分片传输。

piece_size = 4096 # 4 KiB

with open("in-file", "rb") as in_file, open("out-file", "wb") as out_file:
    while True:
        piece = in_file.read(piece_size)

        if piece == "":
            break # end of file

        out_file.write(piece)

在我的示例中,我在打开文件时使用了'b'标志('wb','rb'),因为您说过要读取字节。“b”标志告诉Python不要解释不同操作系统之间可能不同的行尾字符。如果您正在阅读文本,则省略“b”,并分别使用“w”和“r”。

这将使用“最简单”的Python代码在一个块中读取整个文件。这种方法的问题是,读取大文件时可能会耗尽内存:

ifile = open(input_filename,'rb')
ofile = open(output_filename, 'wb')
ofile.write(ifile.read())
ofile.close()
ifile.close()

此示例被优化为读取1MB块,以确保它在不耗尽内存的情况下适用于任何大小的文件:

ifile = open(input_filename,'rb')
ofile = open(output_filename, 'wb')
data = ifile.read(1024*1024)
while data:
    ofile.write(data)
    data = ifile.read(1024*1024)
ofile.close()
ifile.close()

此示例与上面的示例相同,但利用with创建上下文。这种方法的优点是,当退出上下文时,文件会自动关闭:

with open(input_filename,'rb') as ifile:
    with open(output_filename, 'wb') as ofile:
        data = ifile.read(1024*1024)
        while data:
            ofile.write(data)
            data = ifile.read(1024*1024)

请参见以下内容:

相关问题 更多 >